From 62eede88480a70d3b14fa0de6c9f482748733d45 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 19:25:14 +0800 Subject: [PATCH 01/17] Fixed dependencies error --- .github/workflows/js-lint-test.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/js-lint-test.yml b/.github/workflows/js-lint-test.yml index 7917ab787..6391951e4 100644 --- a/.github/workflows/js-lint-test.yml +++ b/.github/workflows/js-lint-test.yml @@ -22,7 +22,6 @@ jobs: uses: actions/setup-node@v4 with: node-version: '20' - cache: 'npm' - name: Install dependencies run: npm install From badc755bfa1ebf828da0680d729ae9a07a5a2ffb Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 19:30:21 +0800 Subject: [PATCH 02/17] Remove tests folder node must be on parent folder --- tests/.gitignore => .gitignore | 0 tests/eslint.config.mjs => eslint.config.mjs | 12 ++++++++++-- tests/jest.config.js => jest.config.js | 0 tests/js-lint-test.yml => js-lint-test.yml | 0 tests/package-lock.json => package-lock.json | 0 tests/package.json => package.json | 0 {tests/unit => unit}/core.test.js | 0 7 files changed, 10 insertions(+), 2 deletions(-) rename tests/.gitignore => .gitignore (100%) rename tests/eslint.config.mjs => eslint.config.mjs (81%) rename tests/jest.config.js => jest.config.js (100%) rename tests/js-lint-test.yml => js-lint-test.yml (100%) rename tests/package-lock.json => package-lock.json (100%) rename tests/package.json => package.json (100%) rename {tests/unit => unit}/core.test.js (100%) diff --git a/tests/.gitignore b/.gitignore similarity index 100% rename from tests/.gitignore rename to .gitignore diff --git a/tests/eslint.config.mjs b/eslint.config.mjs similarity index 81% rename from tests/eslint.config.mjs rename to eslint.config.mjs index 8581f18b7..bc1196fbc 100644 --- a/tests/eslint.config.mjs +++ b/eslint.config.mjs @@ -20,14 +20,22 @@ export default [...compat.extends("eslint:recommended"), { ...globals.webextensions, ...globals.jest, ...globals.worker, - ...globals.wsh + ...globals.wsh, + "ImprovedTube" : false, + "satus": false, + "extension": false, + "loading": false, + "vertical": false, + "shorts": false, + "DATA": false, + "keywords": false } }, rules: { indent: ["error", "tab"], "no-empty": ["error", { "allowEmptyCatch": true }], "no-unused-vars": ["error", { "caughtErrors": "none" }], - "no-undef": ["off"], + //"no-undef": ["off"], "max-len": ["error", { code: 255, ignoreUrls: true, diff --git a/tests/jest.config.js b/jest.config.js similarity index 100% rename from tests/jest.config.js rename to jest.config.js diff --git a/tests/js-lint-test.yml b/js-lint-test.yml similarity index 100% rename from tests/js-lint-test.yml rename to js-lint-test.yml diff --git a/tests/package-lock.json b/package-lock.json similarity index 100% rename from tests/package-lock.json rename to package-lock.json diff --git a/tests/package.json b/package.json similarity index 100% rename from tests/package.json rename to package.json diff --git a/tests/unit/core.test.js b/unit/core.test.js similarity index 100% rename from tests/unit/core.test.js rename to unit/core.test.js From 2c28ecd393a29897dcc7426e53464316937ad1cb Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 20:35:36 +0800 Subject: [PATCH 03/17] . --- eslint.config.mjs | 18 ++++++++---------- unit/core.test.js | 8 ++------ 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index bc1196fbc..aef539513 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -13,6 +13,7 @@ const compat = new FlatCompat({ }); export default [...compat.extends("eslint:recommended"), { + ignores: ["*.mjs"], languageOptions: { globals: { ...globals.browser, @@ -20,22 +21,19 @@ export default [...compat.extends("eslint:recommended"), { ...globals.webextensions, ...globals.jest, ...globals.worker, - ...globals.wsh, - "ImprovedTube" : false, - "satus": false, - "extension": false, - "loading": false, - "vertical": false, - "shorts": false, - "DATA": false, - "keywords": false + ...globals.wsh + }, + parserOptions: { + ecmaFeatures: { + globalReturn : true + } } }, rules: { indent: ["error", "tab"], "no-empty": ["error", { "allowEmptyCatch": true }], "no-unused-vars": ["error", { "caughtErrors": "none" }], - //"no-undef": ["off"], + "no-undef": ["off"], "max-len": ["error", { code: 255, ignoreUrls: true, diff --git a/unit/core.test.js b/unit/core.test.js index 99e23c687..21195bde4 100644 --- a/unit/core.test.js +++ b/unit/core.test.js @@ -1,11 +1,6 @@ // Mock extension object directly within the jest.mock call jest.mock('../../js&css/extension/core', () => ({ domReady: false, - events: { - listeners: {}, - on: jest.fn(), - trigger: jest.fn(), - }, features: {}, functions: {}, messages: { @@ -39,6 +34,7 @@ jest.mock('../../js&css/extension/core', () => ({ events: { // Mock implementation of the events function listeners: {}, + on: jest.fn(), trigger: async function (type, data) { const listeners = this.listeners[type]; @@ -61,7 +57,7 @@ jest.mock('../../js&css/extension/core', () => ({ })); // Mock extension object -const extensionMock = require('../../js&css/extension/core'); +const extensionMock = require('../js&css/extension/core'); // Unit tests for the camelize function test('Convert snake_case to camelCase', () => { From fa3d021087c86e42ea31fc7dde444ba5822cd4be Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 20:38:09 +0800 Subject: [PATCH 04/17] Revert "Fixed code indent" This reverts commit 39658f7d422d4527c9212b3ba135fa38f7e8794b. --- .github/workflows/js-lint-test.yml | 2 +- background.js | 122 +-- jest.config.js | 12 +- js&css/extension/init.js | 52 +- .../www.youtube.com/general/general.js | 304 +++---- js&css/web-accessible/core.js | 332 ++++---- js&css/web-accessible/functions.js | 91 +-- .../www.youtube.com/appearance.js | 747 +++++++++--------- .../www.youtube.com/blocklist.js | 92 +-- .../web-accessible/www.youtube.com/channel.js | 38 +- .../web-accessible/www.youtube.com/player.js | 422 +++++----- .../www.youtube.com/playlist.js | 82 +- .../www.youtube.com/shortcuts.js | 46 +- .../web-accessible/www.youtube.com/themes.js | 104 +-- menu/index.js | 2 +- menu/satus.js | 82 +- menu/skeleton-parts/appearance.js | 490 ++++++------ menu/skeleton-parts/blocklist.js | 16 +- menu/skeleton-parts/dark-light-switch.js | 86 +- menu/skeleton-parts/general.js | 36 +- menu/skeleton-parts/player.js | 6 +- menu/skeleton-parts/themes.js | 16 +- unit/core.test.js | 98 +-- 23 files changed, 1640 insertions(+), 1638 deletions(-) diff --git a/.github/workflows/js-lint-test.yml b/.github/workflows/js-lint-test.yml index 6391951e4..856fcdcab 100644 --- a/.github/workflows/js-lint-test.yml +++ b/.github/workflows/js-lint-test.yml @@ -26,7 +26,7 @@ jobs: - name: Install dependencies run: npm install - - name: Run eslint + - name: Install dependencies run: npx eslint continue-on-error: true diff --git a/background.js b/background.js index aeee3cdb0..311e4040a 100644 --- a/background.js +++ b/background.js @@ -253,38 +253,38 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { //console.log(sender); switch(message.action || message.name || message) { - case 'play': - tabPrune(function () { - for (let id in tabConnected) { - id = Number(id); - if (id != sender.tab.id) { - chrome.tabs.sendMessage(id, {action: "another-video-started-playing"}); + case 'play': + tabPrune(function () { + for (let id in tabConnected) { + id = Number(id); + if (id != sender.tab.id) { + chrome.tabs.sendMessage(id, {action: "another-video-started-playing"}); + } } - } - }); - break + }); + break - case 'options-page-connected': - sendResponse({ - isTab: sender.hasOwnProperty('tab') - }); - break + case 'options-page-connected': + sendResponse({ + isTab: sender.hasOwnProperty('tab') + }); + break - case 'tab-connected': - tabConnected[sender.tab.id] = true; - sendResponse({ - tabId: sender.tab.id - }); - break + case 'tab-connected': + tabConnected[sender.tab.id] = true; + sendResponse({ + tabId: sender.tab.id + }); + break - case 'fixPopup': - //~ get the current focused tab and convert it to a URL-less popup (with same state and size) - chrome.windows.getLastFocused(w => { - chrome.tabs.query({ - windowId: w.id, - active: true - }, ts => { - const tID = ts[0]?.id, + case 'fixPopup': + //~ get the current focused tab and convert it to a URL-less popup (with same state and size) + chrome.windows.getLastFocused(w => { + chrome.tabs.query({ + windowId: w.id, + active: true + }, ts => { + const tID = ts[0]?.id, data = { type: 'popup', state: w.state, width: parseInt(message.width, 10), @@ -293,42 +293,42 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { top: 20 } - if (tID) {data.tabId = tID;} - chrome.windows.create(data, pw => {}); + if (tID) {data.tabId = tID;} + chrome.windows.create(data, pw => {}); - //append to title? - chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) { - if (tabId === tID && changeInfo.status === 'complete' && !message.title.startsWith("undefined")) { - chrome.tabs.onUpdated.removeListener(listener); - chrome.scripting.executeScript({ target: { tabId: tID }, func: () => { document.title = `${message.title} - ImprovedTube`; } }); //manifest3 - // chrome.tabs.executeScript(tID, {code: `document.title = "${message.title} - ImprovedTube";`}); //manifest2 - } + //append to title? + chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) { + if (tabId === tID && changeInfo.status === 'complete' && !message.title.startsWith("undefined")) { + chrome.tabs.onUpdated.removeListener(listener); + chrome.scripting.executeScript({ target: { tabId: tID }, func: () => { document.title = `${message.title} - ImprovedTube`; } }); //manifest3 + // chrome.tabs.executeScript(tID, {code: `document.title = "${message.title} - ImprovedTube";`}); //manifest2 + } + }); }); }); - }); - break - case 'download': - chrome.permissions.request({ - permissions: ['downloads'], - origins: ['https://www.youtube.com/*'] - }, function (granted) { - if (granted) { - try { - var blob = new Blob([JSON.stringify(message.value)], { - type: 'application/json;charset=utf-8' - }); - chrome.downloads.download({ - url: URL.createObjectURL(blob), - filename: message.filename, - saveAs: true - }); - } catch (error) { - console.error(error); - } - } else { - console.error('Permission is not granted.'); - }}) - break + break + case 'download': + chrome.permissions.request({ + permissions: ['downloads'], + origins: ['https://www.youtube.com/*'] + }, function (granted) { + if (granted) { + try { + var blob = new Blob([JSON.stringify(message.value)], { + type: 'application/json;charset=utf-8' + }); + chrome.downloads.download({ + url: URL.createObjectURL(blob), + filename: message.filename, + saveAs: true + }); + } catch (error) { + console.error(error); + } + } else { + console.error('Permission is not granted.'); + }}) + break } }); /*-----# UNINSTALL URL-----------------------------------*/ diff --git a/jest.config.js b/jest.config.js index 5e9923b5e..0ad591433 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,8 +1,8 @@ module.exports = { - testPathIgnorePatterns: [ - "/node_modules/" - ], - testMatch: [ - "**/tests/**/*.js" - ] + testPathIgnorePatterns: [ + "/node_modules/" + ], + testMatch: [ + "**/tests/**/*.js" + ] }; diff --git a/js&css/extension/init.js b/js&css/extension/init.js index 14f098629..b6f5e5116 100644 --- a/js&css/extension/init.js +++ b/js&css/extension/init.js @@ -180,34 +180,34 @@ document.addEventListener('it-message-from-youtube', function () { } switch(message.type) { - case 'channel': - if (!extension.storage.data.blocklist.channels || typeof extension.storage.data.blocklist.channels !== 'object') { - extension.storage.data.blocklist.channels = {}; - } - if (message.added) { - extension.storage.data.blocklist.channels[message.id] = { - title: message.title, - preview: message.preview, - when: message.when + case 'channel': + if (!extension.storage.data.blocklist.channels || typeof extension.storage.data.blocklist.channels !== 'object') { + extension.storage.data.blocklist.channels = {}; } - } else { - delete extension.storage.data.blocklist.channels[message.id]; - } - break + if (message.added) { + extension.storage.data.blocklist.channels[message.id] = { + title: message.title, + preview: message.preview, + when: message.when + } + } else { + delete extension.storage.data.blocklist.channels[message.id]; + } + break - case 'video': - if (!extension.storage.data.blocklist.videos || typeof extension.storage.data.blocklist.videos !== 'object') { - extension.storage.data.blocklist.videos = {}; - } - if (message.added) { - extension.storage.data.blocklist.videos[message.id] = { - title: message.title, - when: message.when + case 'video': + if (!extension.storage.data.blocklist.videos || typeof extension.storage.data.blocklist.videos !== 'object') { + extension.storage.data.blocklist.videos = {}; } - } else { - delete extension.storage.data.blocklist.videos[message.id]; - } - break + if (message.added) { + extension.storage.data.blocklist.videos[message.id] = { + title: message.title, + when: message.when + } + } else { + delete extension.storage.data.blocklist.videos[message.id]; + } + break } chrome.storage.local.set({ @@ -244,5 +244,5 @@ document.addEventListener('it-message-from-youtube', function () { document.addEventListener('it-play', function (event) { var videos = document.querySelectorAll('video'); try {chrome.runtime.sendMessage({action: 'play'})} - catch(error){console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } + catch(error){console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } }); diff --git a/js&css/extension/www.youtube.com/general/general.js b/js&css/extension/www.youtube.com/general/general.js index 33eee3cc2..a6a06d4b6 100644 --- a/js&css/extension/www.youtube.com/general/general.js +++ b/js&css/extension/www.youtube.com/general/general.js @@ -154,36 +154,36 @@ extension.features.onlyOnePlayerInstancePlaying = function () { # ADD "SCROLL TO TOP" --------------------------------------------------------------*/ extension.features.addScrollToTop = function (event) { - if (event instanceof Event) { - if (window.scrollY > window.innerHeight / 2) { - document.documentElement.setAttribute('it-scroll-to-top', 'true'); - } else { - document.documentElement.removeAttribute('it-scroll-to-top'); - } - } else { - if (extension.storage.get('add_scroll_to_top') === true) { - this.addScrollToTop.button = document.createElement('div'); - this.addScrollToTop.button.id = 'it-scroll-to-top'; - this.addScrollToTop.button.className = 'satus-div'; - var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - svg.setAttribute('viewBox', '0 0 24 24'); - var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttribute('d', 'M13 19V7.8l4.9 5c.4.3 1 .3 1.4 0 .4-.5.4-1.1 0-1.5l-6.6-6.6a1 1 0 0 0-1.4 0l-6.6 6.6a1 1 0 1 0 1.4 1.4L11 7.8V19c0 .6.5 1 1 1s1-.5 1-1z'); - svg.appendChild(path); - this.addScrollToTop.button.appendChild(svg); - window.addEventListener('scroll', function () { document.body.appendChild(extension.features.addScrollToTop.button); }); - this.addScrollToTop.button.addEventListener('click', function () { - window.scrollTo(0, 0); - document.getElementById('it-scroll-to-top')?.remove(); - }); - } - if (extension.storage.get('add_scroll_to_top') === true) { - window.addEventListener('scroll', extension.features.addScrollToTop); - } else if (this.addScrollToTop.button) { - window.removeEventListener('scroll', extension.features.addScrollToTop); - this.addScrollToTop.button.remove(); - } - } + if (event instanceof Event) { + if (window.scrollY > window.innerHeight / 2) { + document.documentElement.setAttribute('it-scroll-to-top', 'true'); + } else { + document.documentElement.removeAttribute('it-scroll-to-top'); + } + } else { + if (extension.storage.get('add_scroll_to_top') === true) { + this.addScrollToTop.button = document.createElement('div'); + this.addScrollToTop.button.id = 'it-scroll-to-top'; + this.addScrollToTop.button.className = 'satus-div'; + var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('d', 'M13 19V7.8l4.9 5c.4.3 1 .3 1.4 0 .4-.5.4-1.1 0-1.5l-6.6-6.6a1 1 0 0 0-1.4 0l-6.6 6.6a1 1 0 1 0 1.4 1.4L11 7.8V19c0 .6.5 1 1 1s1-.5 1-1z'); + svg.appendChild(path); + this.addScrollToTop.button.appendChild(svg); + window.addEventListener('scroll', function () { document.body.appendChild(extension.features.addScrollToTop.button); }); + this.addScrollToTop.button.addEventListener('click', function () { + window.scrollTo(0, 0); + document.getElementById('it-scroll-to-top')?.remove(); + }); + } + if (extension.storage.get('add_scroll_to_top') === true) { + window.addEventListener('scroll', extension.features.addScrollToTop); + } else if (this.addScrollToTop.button) { + window.removeEventListener('scroll', extension.features.addScrollToTop); + this.addScrollToTop.button.remove(); + } + } }; /*-------------------------------------------------------------- # CONFIRMATION BEFORE CLOSING @@ -238,40 +238,40 @@ extension.features.popupWindowButtons = function (event) { || (target.className.indexOf('video-preview') !== -1 || target.className.indexOf('ytp-inline-preview-scrim') !== -1 || target.className.indexOf('ytp-inline-preview-ui') !== -1) )) { if (!target.itPopupWindowButton) { - target.itPopupWindowButton = document.createElement('button'); - target.itPopupWindowButton.className = 'it-popup-window'; - - var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - svg.setAttribute('viewBox', '0 0 24 24'); - var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttribute('d', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z'); - svg.appendChild(path); - target.itPopupWindowButton.appendChild(svg); - target.appendChild(target.itPopupWindowButton); - - target.itPopupWindowButton.addEventListener('click', function (event) { - event.preventDefault(); - event.stopPropagation(); - try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch(error) { console.log(error)}; - ytPlayer = document.querySelector("#movie_player"); - if (ytPlayer){width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} - else { width = innerWidth * 0.4; height = innerHeight * 0.4; } +target.itPopupWindowButton = document.createElement('button'); +target.itPopupWindowButton.className = 'it-popup-window'; + +var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); +svg.setAttribute('viewBox', '0 0 24 24'); +var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); +path.setAttribute('d', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z'); +svg.appendChild(path); +target.itPopupWindowButton.appendChild(svg); +target.appendChild(target.itPopupWindowButton); + +target.itPopupWindowButton.addEventListener('click', function (event) { + event.preventDefault(); + event.stopPropagation(); + try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch(error) { console.log(error)}; + ytPlayer = document.querySelector("#movie_player"); + if (ytPlayer){width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} + else { width = innerWidth * 0.4; height = innerHeight * 0.4; } if (!ytPlayer) { - let shorts = /short/.test(this.parentElement.href); - if ( width / height < 1 ) { let vertical = true } else { let vertical = false } - if ( !vertical && shorts ){ width = height * 0.6} - if ( vertical && !shorts ){ height = width * 0.6} - } + let shorts = /short/.test(this.parentElement.href); + if ( width / height < 1 ) { let vertical = true } else { let vertical = false } + if ( !vertical && shorts ){ width = height * 0.6} + if ( vertical && !shorts ){ height = width * 0.6} + } - window.open('https://www.youtube.com/embed/' + this.dataset.id + '?autoplay=' + (extension.storage.get('player_autoplay_disable') ? '0' : '1'), '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); - chrome.runtime.sendMessage({ - action: 'fixPopup', - width: width, - height: height, - title: this.parentElement.closest('*[id="video-title"]')?.textContent + " - Youtube" - }) - }); - } + window.open('https://www.youtube.com/embed/' + this.dataset.id + '?autoplay=' + (extension.storage.get('player_autoplay_disable') ? '0' : '1'), '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); + chrome.runtime.sendMessage({ + action: 'fixPopup', + width: width, + height: height, + title: this.parentElement.closest('*[id="video-title"]')?.textContent + " - Youtube" + }) + }); + } detected = true; } target = target.parentNode; @@ -344,46 +344,46 @@ extension.features.markWatchedVideos = function (anything) { ) ) { if (!target.itMarkWatchedVideosButton) { - target.itMarkWatchedVideosButton = document.createElement('button'); - target.itMarkWatchedVideosButton.className = 'it-mark-watched-videos'; - target.itMarkWatchedVideosButton.dataset.id = extension.functions.getUrlParameter(target.href, 'v'); - var id = target.itMarkWatchedVideosButton.dataset.id; - var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); - var pathData = 'M12 15.15q1.525 0 2.588-1.063 1.062-1.062 1.062-2.587 0-1.525-1.062-2.588Q13.525 7.85 12 7.85q-1.525 0-2.587 1.062Q8.35 9.975 8.35 11.5q0 1.525 1.063 2.587Q10.475 15.15 12 15.15Zm0-.95q-1.125 0-1.912-.788Q9.3 12.625 9.3 11.5t.788-1.913Q10.875 8.8 12 8.8t1.913.787q.787.788.787 1.913t-.787 1.912q-.788.788-1.913.788Zm0 3.8q-3.1 0-5.688-1.613Q3.725 14.775 2.325 12q-.05-.1-.075-.225-.025-.125-.025-.275 0-.15.025-.275.025-.125.075-.225 1.4-2.775 3.987-4.388Q8.9 5 12 5q3.1 0 5.688 1.612Q20.275 8.225 21.675 11q.05.1.075.225.025.125.025.275 0 .15-.025.275-.025.125-.075.225-1.4 2.775-3.987 4.387Q15.1 18 12 18Z'; - var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttribute('d', pathData + 'm0-6.5Zm0 5.5q2.825 0 5.188-1.488Q19.55 14.025 20.8 11.5q-1.25-2.525-3.612-4.013Q14.825 6 12 6 9.175 6 6.812 7.487 4.45 8.975 3.2 11.5q1.25 2.525 3.612 4.012Q9.175 17 12 17Z'); - svg.appendChild(path); - var svg2 = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg2.setAttribute('viewBox', '0 0 24 24'); - var extraPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - extraPath.setAttribute('d', pathData); - svg2.appendChild(extraPath); - target.itMarkWatchedVideosButton.appendChild(svg); - target.itMarkWatchedVideosButton.appendChild(svg2); - if (extension.storage.get('watched') && extension.storage.get('watched')[id]) { - target.itMarkWatchedVideosButton.setAttribute('watched', '')}; - target.appendChild(target.itMarkWatchedVideosButton); - target.itMarkWatchedVideosButton.addEventListener('click', function (event) { - var id = this.dataset.id, - value = this.toggleAttribute('watched'); - - event.preventDefault(); - event.stopPropagation(); - - if (!extension.storage.watched) { - extension.storage.watched = {}; - } - - if (value) { - extension.storage.get('watched')[id] = { - title: '' - }; - } else { - delete extension.storage.get('watched')[id]; - } - - chrome.storage.local.set({ - watched: extension.storage.get('watched') - });}); + target.itMarkWatchedVideosButton = document.createElement('button'); + target.itMarkWatchedVideosButton.className = 'it-mark-watched-videos'; + target.itMarkWatchedVideosButton.dataset.id = extension.functions.getUrlParameter(target.href, 'v'); + var id = target.itMarkWatchedVideosButton.dataset.id; + var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); + var pathData = 'M12 15.15q1.525 0 2.588-1.063 1.062-1.062 1.062-2.587 0-1.525-1.062-2.588Q13.525 7.85 12 7.85q-1.525 0-2.587 1.062Q8.35 9.975 8.35 11.5q0 1.525 1.063 2.587Q10.475 15.15 12 15.15Zm0-.95q-1.125 0-1.912-.788Q9.3 12.625 9.3 11.5t.788-1.913Q10.875 8.8 12 8.8t1.913.787q.787.788.787 1.913t-.787 1.912q-.788.788-1.913.788Zm0 3.8q-3.1 0-5.688-1.613Q3.725 14.775 2.325 12q-.05-.1-.075-.225-.025-.125-.025-.275 0-.15.025-.275.025-.125.075-.225 1.4-2.775 3.987-4.388Q8.9 5 12 5q3.1 0 5.688 1.612Q20.275 8.225 21.675 11q.05.1.075.225.025.125.025.275 0 .15-.025.275-.025.125-.075.225-1.4 2.775-3.987 4.387Q15.1 18 12 18Z'; + var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('d', pathData + 'm0-6.5Zm0 5.5q2.825 0 5.188-1.488Q19.55 14.025 20.8 11.5q-1.25-2.525-3.612-4.013Q14.825 6 12 6 9.175 6 6.812 7.487 4.45 8.975 3.2 11.5q1.25 2.525 3.612 4.012Q9.175 17 12 17Z'); + svg.appendChild(path); + var svg2 = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg2.setAttribute('viewBox', '0 0 24 24'); + var extraPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + extraPath.setAttribute('d', pathData); + svg2.appendChild(extraPath); + target.itMarkWatchedVideosButton.appendChild(svg); + target.itMarkWatchedVideosButton.appendChild(svg2); + if (extension.storage.get('watched') && extension.storage.get('watched')[id]) { + target.itMarkWatchedVideosButton.setAttribute('watched', '')}; + target.appendChild(target.itMarkWatchedVideosButton); + target.itMarkWatchedVideosButton.addEventListener('click', function (event) { + var id = this.dataset.id, + value = this.toggleAttribute('watched'); + + event.preventDefault(); + event.stopPropagation(); + + if (!extension.storage.watched) { + extension.storage.watched = {}; + } + + if (value) { + extension.storage.get('watched')[id] = { + title: '' + }; + } else { + delete extension.storage.get('watched')[id]; + } + + chrome.storage.local.set({ + watched: extension.storage.get('watched') + });}); } else { var button = target.itMarkWatchedVideosButton; @@ -516,18 +516,18 @@ extension.features.thumbnailsQuality = function (anything) { # DISABLE VIDEO PLAYBACK ON HOVER --------------------------------------------------------------*/ extension.features.disableThumbnailPlayback = function (event) { - if (event instanceof Event) { - if (event.composedPath().some(elem => (elem.matches != null && elem.matches('#content.ytd-rich-item-renderer, #contents.ytd-item-section-renderer')) - )) { - event.stopImmediatePropagation(); - } - } else { - if (extension.storage.get('disable_thumbnail_playback') === true) { - window.addEventListener('mouseenter', this.disableThumbnailPlayback, true); - } else { - window.removeEventListener('mouseenter', this.disableThumbnailPlayback, true); - } - } + if (event instanceof Event) { + if (event.composedPath().some(elem => (elem.matches != null && elem.matches('#content.ytd-rich-item-renderer, #contents.ytd-item-section-renderer')) + )) { + event.stopImmediatePropagation(); + } + } else { + if (extension.storage.get('disable_thumbnail_playback') === true) { + window.addEventListener('mouseenter', this.disableThumbnailPlayback, true); + } else { + window.removeEventListener('mouseenter', this.disableThumbnailPlayback, true); + } + } }; /*-------------------------------------------------------------- @@ -536,50 +536,50 @@ extension.features.disableThumbnailPlayback = function (event) { extension.features.openNewTab = function (){ if (extension.storage.get("open_new_tab") === true) { - window.onload = function () { - const searchButton = document.querySelector("button#search-icon-legacy"); - const inputField = document.querySelector("input#search"); + window.onload = function () { + const searchButton = document.querySelector("button#search-icon-legacy"); + const inputField = document.querySelector("input#search"); - searchButton.addEventListener("mousedown", (event) => { + searchButton.addEventListener("mousedown", (event) => { performSearchNewTab(inputField.value); }); - inputField.addEventListener("keydown", function (event) { - if (event.key === "Enter") { - performSearchNewTab(inputField.value); - } - }); - + inputField.addEventListener("keydown", function (event) { + if (event.key === "Enter") { + performSearchNewTab(inputField.value); + } + }); - let searchedAlready = false; - inputField.addEventListener("focus", function () { - searchedAlready = false; - const observer = new MutationObserver(applySuggestionListeners); - const container = document.querySelector("div[style*='position: fixed'] ul[role='listbox']"); - if (container) observer.observe(container, { attributes: true, childList: true, subtree: true }); - }); - inputField.addEventListener("input", () => searchedAlready = false); - - function applySuggestionListeners() { - const suggestionContainers = document.querySelectorAll("div[class^='sbqs'], div[class^='sbpqs']"); - suggestionContainers.forEach((suggestionsContainer) => { - suggestionsContainer.addEventListener("mousedown", (event) => { - const suggestionListItem = event.target.closest("li[role='presentation']"); - if (suggestionListItem && !searchedAlready) { - const query = suggestionListItem.querySelector("b").textContent - performSearchNewTab(inputField.value + query); - searchedAlready = true; - } - }); - }); - } + let searchedAlready = false; + inputField.addEventListener("focus", function () { + searchedAlready = false; + const observer = new MutationObserver(applySuggestionListeners); + const container = document.querySelector("div[style*='position: fixed'] ul[role='listbox']"); + if (container) observer.observe(container, { attributes: true, childList: true, subtree: true }); +}); + + inputField.addEventListener("input", () => searchedAlready = false); + + function applySuggestionListeners() { + const suggestionContainers = document.querySelectorAll("div[class^='sbqs'], div[class^='sbpqs']"); + suggestionContainers.forEach((suggestionsContainer) => { + suggestionsContainer.addEventListener("mousedown", (event) => { + const suggestionListItem = event.target.closest("li[role='presentation']"); + if (suggestionListItem && !searchedAlready) { + const query = suggestionListItem.querySelector("b").textContent + performSearchNewTab(inputField.value + query); + searchedAlready = true; + } + }); + }); +} - function performSearchNewTab(query) { - inputField.value = ""; - inputField.focus(); - const newTabURL = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`; - window.open(newTabURL, '_blank'); - } + function performSearchNewTab(query) { + inputField.value = ""; + inputField.focus(); + const newTabURL = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`; + window.open(newTabURL, '_blank'); } } + } } diff --git a/js&css/web-accessible/core.js b/js&css/web-accessible/core.js index ee864b7c5..6075d832a 100644 --- a/js&css/web-accessible/core.js +++ b/js&css/web-accessible/core.js @@ -181,7 +181,7 @@ document.addEventListener('it-message-from-extension', function () { if (ImprovedTube.storage.block_vp9 || ImprovedTube.storage.block_av1 || ImprovedTube.storage.block_h264) { let atlas = {block_vp9:'vp9|vp09', block_h264:'avc1', block_av1:'av01'}, codec = Object.keys(atlas).reduce(function (all, key) { - return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all}, ''); + return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all}, ''); if (localStorage['it-codec'] != codec) { localStorage['it-codec'] = codec; } @@ -221,183 +221,183 @@ document.addEventListener('it-message-from-extension', function () { } switch(camelized_key) { - case 'blocklist': - case 'blocklistActivate': - ImprovedTube.blocklistInit(); - break - - case 'playerPlaybackSpeed': - case 'playerForcedPlaybackSpeed': - if (ImprovedTube.storage.player_forced_playback_speed === true) { - ImprovedTube.elements.player.setPlaybackRate(Number(ImprovedTube.storage.player_playback_speed)); - ImprovedTube.elements.player.querySelector('video').playbackRate = Number(ImprovedTube.storage.player_playback_speed); - } else if (ImprovedTube.storage.player_forced_playback_speed === false) { - ImprovedTube.elements.player.setPlaybackRate(1); - ImprovedTube.elements.player.querySelector('video').playbackRate = 1; - } - break - - case 'theme': - case 'themePrimaryColor': - case 'themeTextColor': - ImprovedTube.myColors(); - ImprovedTube.setTheme(); - break - - case 'description': - if (ImprovedTube.storage.description === "expanded" || ImprovedTube.storage.description === "classic_expanded") { - try{document.querySelector("#more").click() || document.querySelector("#expand").click();} catch{} - } else if (ImprovedTube.storage.description === "normal" || ImprovedTube.storage.description === "classic") { - try{document.querySelector("#less").click() || document.querySelector("#collapse").click();} catch{} - } - break - - case 'transcript': - if (ImprovedTube.storage.transcript === true) { - document.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility'); - } else if (ImprovedTube.storage.transcript === false) { - document.querySelector('*[target-id*=transcript] #visibility-button button')?.click(); - } - break - - case 'chapters': - if (ImprovedTube.storage.chapters === true) { - document.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility'); - } else if (ImprovedTube.storage.chapters === false) { - document.querySelector('*[target-id*=chapters] #visibility-button button')?.click(); - } - break - - case 'commentsSidebarSimple': - if (ImprovedTube.storage.comments_sidebar_simple === false) { - document.querySelector("#below").appendChild(document.querySelector("#comments")); - document.querySelector("#secondary").appendChild(document.querySelector("#related")); - } else { - ImprovedTube.commentsSidebarSimple(); - } - break - - case 'forcedTheaterMode': - if (ImprovedTube.storage.forced_theater_mode === false && ImprovedTube.elements.ytd_watch && ImprovedTube.elements.player) { - var button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); - if (button && ImprovedTube.elements.ytd_watch.theater === true) { - ImprovedTube.elements.ytd_watch.theater = false; - setTimeout(function () { button.click();}, 100); + case 'blocklist': + case 'blocklistActivate': + ImprovedTube.blocklistInit(); + break + + case 'playerPlaybackSpeed': + case 'playerForcedPlaybackSpeed': + if (ImprovedTube.storage.player_forced_playback_speed === true) { + ImprovedTube.elements.player.setPlaybackRate(Number(ImprovedTube.storage.player_playback_speed)); + ImprovedTube.elements.player.querySelector('video').playbackRate = Number(ImprovedTube.storage.player_playback_speed); + } else if (ImprovedTube.storage.player_forced_playback_speed === false) { + ImprovedTube.elements.player.setPlaybackRate(1); + ImprovedTube.elements.player.querySelector('video').playbackRate = 1; } - } - break + break + + case 'theme': + case 'themePrimaryColor': + case 'themeTextColor': + ImprovedTube.myColors(); + ImprovedTube.setTheme(); + break + + case 'description': + if (ImprovedTube.storage.description === "expanded" || ImprovedTube.storage.description === "classic_expanded") { + try{document.querySelector("#more").click() || document.querySelector("#expand").click();} catch{} + } else if (ImprovedTube.storage.description === "normal" || ImprovedTube.storage.description === "classic") { + try{document.querySelector("#less").click() || document.querySelector("#collapse").click();} catch{} + } + break - case 'playerScreenshotButton': - if (ImprovedTube.storage.player_screenshot_button === false) { - if (ImprovedTube.elements.buttons['it-screenshot-button']) { - ImprovedTube.elements.buttons['it-screenshot-button']?.remove(); - ImprovedTube.elements.buttons['it-screenshot-styles']?.remove(); + case 'transcript': + if (ImprovedTube.storage.transcript === true) { + document.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility'); + } else if (ImprovedTube.storage.transcript === false) { + document.querySelector('*[target-id*=transcript] #visibility-button button')?.click(); } - } - break + break - case 'playerRepeatButton': - if (ImprovedTube.storage.player_repeat_button === false) { - if (ImprovedTube.elements.buttons['it-repeat-button']) { - ImprovedTube.elements.buttons['it-repeat-button']?.remove(); - ImprovedTube.elements.buttons['it-repeat-styles']?.remove(); + case 'chapters': + if (ImprovedTube.storage.chapters === true) { + document.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility'); + } else if (ImprovedTube.storage.chapters === false) { + document.querySelector('*[target-id*=chapters] #visibility-button button')?.click(); } - } - break + break + + case 'commentsSidebarSimple': + if (ImprovedTube.storage.comments_sidebar_simple === false) { + document.querySelector("#below").appendChild(document.querySelector("#comments")); + document.querySelector("#secondary").appendChild(document.querySelector("#related")); + } else { + ImprovedTube.commentsSidebarSimple(); + } + break + + case 'forcedTheaterMode': + if (ImprovedTube.storage.forced_theater_mode === false && ImprovedTube.elements.ytd_watch && ImprovedTube.elements.player) { + var button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); + if (button && ImprovedTube.elements.ytd_watch.theater === true) { + ImprovedTube.elements.ytd_watch.theater = false; + setTimeout(function () { button.click();}, 100); + } + } + break + + case 'playerScreenshotButton': + if (ImprovedTube.storage.player_screenshot_button === false) { + if (ImprovedTube.elements.buttons['it-screenshot-button']) { + ImprovedTube.elements.buttons['it-screenshot-button']?.remove(); + ImprovedTube.elements.buttons['it-screenshot-styles']?.remove(); + } + } + break + + case 'playerRepeatButton': + if (ImprovedTube.storage.player_repeat_button === false) { + if (ImprovedTube.elements.buttons['it-repeat-button']) { + ImprovedTube.elements.buttons['it-repeat-button']?.remove(); + ImprovedTube.elements.buttons['it-repeat-styles']?.remove(); + } + } + break - case 'playerPopupButton': - if (ImprovedTube.storage.player_popup_button === false) { - ImprovedTube.elements.buttons['it-popup-player-button']?.remove(); - } - break + case 'playerPopupButton': + if (ImprovedTube.storage.player_popup_button === false) { + ImprovedTube.elements.buttons['it-popup-player-button']?.remove(); + } + break - case 'playerRotateButton': - if (ImprovedTube.storage.player_rotate_button === false) { - ImprovedTube.elements.buttons['it-rotate-button']?.remove(); - ImprovedTube.elements.buttons['it-rotate-styles']?.remove(); - } - break + case 'playerRotateButton': + if (ImprovedTube.storage.player_rotate_button === false) { + ImprovedTube.elements.buttons['it-rotate-button']?.remove(); + ImprovedTube.elements.buttons['it-rotate-styles']?.remove(); + } + break - case 'playerFitToWinButton': - if (ImprovedTube.storage.player_fit_to_win_button === false) { - ImprovedTube.elements.buttons['it-fit-to-win-player-button']?.remove(); - document.querySelector("html")?.setAttribute("it-player-size", ImprovedTube.storage.player_size ?? "do_not_change"); - } - break - - case 'playerHamburgerButton': - if (ImprovedTube.storage.player_hamburger_button == false) { - document.querySelector('.custom-hamburger-menu')?.remove(); - let rightControls = document.querySelector('.html5-video-player')?.querySelector('.ytp-right-controls'); - if (rightControls) { - rightControls.style.setProperty('padding-right', ''); // Restoring the original padding: - rightControls.style.setProperty('display', 'flex'); + case 'playerFitToWinButton': + if (ImprovedTube.storage.player_fit_to_win_button === false) { + ImprovedTube.elements.buttons['it-fit-to-win-player-button']?.remove(); + document.querySelector("html")?.setAttribute("it-player-size", ImprovedTube.storage.player_size ?? "do_not_change"); } - } - break - - case 'belowPlayerPip': - if (ImprovedTube.storage.below_player_pip === false) { - document.querySelector('.improvedtube-player-button[data-tooltip="PiP"]')?.remove(); - } else if (ImprovedTube.storage.below_player_pip === true) { - document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); - ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); - } - break - - case 'belowPlayerScreenshot': - if (ImprovedTube.storage.below_player_screenshot === false) { - document.querySelector('.improvedtube-player-button[data-tooltip="Screenshot"]')?.remove(); - } else if (ImprovedTube.storage.below_player_screenshot === true) { - document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); - ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); - } - break - - case 'belowPlayerLoop': - if (ImprovedTube.storage.below_player_loop === false) { - document.querySelector('.improvedtube-player-button[data-tooltip="Loop"]')?.remove(); - } else if (ImprovedTube.storage.below_player_loop === true) { - document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); - ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); - } - break + break + + case 'playerHamburgerButton': + if (ImprovedTube.storage.player_hamburger_button == false) { + document.querySelector('.custom-hamburger-menu')?.remove(); + let rightControls = document.querySelector('.html5-video-player')?.querySelector('.ytp-right-controls'); + if (rightControls) { + rightControls.style.setProperty('padding-right', ''); // Restoring the original padding: + rightControls.style.setProperty('display', 'flex'); + } + } + break + + case 'belowPlayerPip': + if (ImprovedTube.storage.below_player_pip === false) { + document.querySelector('.improvedtube-player-button[data-tooltip="PiP"]')?.remove(); + } else if (ImprovedTube.storage.below_player_pip === true) { + document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); + ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); + } + break + + case 'belowPlayerScreenshot': + if (ImprovedTube.storage.below_player_screenshot === false) { + document.querySelector('.improvedtube-player-button[data-tooltip="Screenshot"]')?.remove(); + } else if (ImprovedTube.storage.below_player_screenshot === true) { + document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); + ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); + } + break + + case 'belowPlayerLoop': + if (ImprovedTube.storage.below_player_loop === false) { + document.querySelector('.improvedtube-player-button[data-tooltip="Loop"]')?.remove(); + } else if (ImprovedTube.storage.below_player_loop === true) { + document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); + ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); + } + break - case 'dayOfWeek': - if (ImprovedTube.storage.day_of_week === false) { - document.querySelector(".ytd-day-of-week")?.remove(); - } else if (ImprovedTube.storage.day_of_week === true) { - ImprovedTube.dayOfWeek(); - } - break + case 'dayOfWeek': + if (ImprovedTube.storage.day_of_week === false) { + document.querySelector(".ytd-day-of-week")?.remove(); + } else if (ImprovedTube.storage.day_of_week === true) { + ImprovedTube.dayOfWeek(); + } + break - case 'playerRemainingDuration': - if (ImprovedTube.storage.player_remaining_duration === false) { - document.querySelector(".ytp-time-remaining-duration")?.remove(); - } else if (ImprovedTube.storage.player_remaining_duration === true) { - ImprovedTube.playerRemainingDuration(); - } - break - - case 'subtitlesFontFamily': - case 'subtitlesFontColor': - case 'subtitlesFontSize': - case 'subtitlesBackgroundColor': - case 'subtitlesWindowColor': - case 'subtitlesWindowOpacity': - case 'subtitlesCharacterEdgeStyle': - case 'subtitlesFontOpacity': - case 'subtitlesBackgroundOpacity': - ImprovedTube.subtitlesUserSettings(); - break + case 'playerRemainingDuration': + if (ImprovedTube.storage.player_remaining_duration === false) { + document.querySelector(".ytp-time-remaining-duration")?.remove(); + } else if (ImprovedTube.storage.player_remaining_duration === true) { + ImprovedTube.playerRemainingDuration(); + } + break + + case 'subtitlesFontFamily': + case 'subtitlesFontColor': + case 'subtitlesFontSize': + case 'subtitlesBackgroundColor': + case 'subtitlesWindowColor': + case 'subtitlesWindowOpacity': + case 'subtitlesCharacterEdgeStyle': + case 'subtitlesFontOpacity': + case 'subtitlesBackgroundOpacity': + ImprovedTube.subtitlesUserSettings(); + break - case 'playerHideControls': - ImprovedTube.playerControls(); - break - case 'playerlistUpNextAutoplay': - if (this.storage.playlist_up_next_autoplay !== false) { - if (playlistData.currentIndex != playlistData.localCurrentIndex) { playlistData.currentIndex = playlistData.localCurrentIndex;} } - break + case 'playerHideControls': + ImprovedTube.playerControls(); + break + case 'playerlistUpNextAutoplay': + if (this.storage.playlist_up_next_autoplay !== false) { + if (playlistData.currentIndex != playlistData.localCurrentIndex) { playlistData.currentIndex = playlistData.localCurrentIndex;} } + break } // dont trigger shortcuts on config change, reinitialize handler instead diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index dc13ea260..b504d9aab 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -59,7 +59,7 @@ ImprovedTube.ytElementsHandler = function (node) { try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} catch{try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} catch{try{this.elements.playlist.actions = node.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode;} + catch{try{this.elements.playlist.actions = node.parentNode;} catch{try{this.elements.playlist.actions = node;}catch{}} } } @@ -76,7 +76,7 @@ ImprovedTube.ytElementsHandler = function (node) { try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} catch{try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} catch{try{this.elements.playlist.actions = node.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode;} + catch{try{this.elements.playlist.actions = node.parentNode;} catch{try{this.elements.playlist.actions = node;}catch{}} } } @@ -126,9 +126,9 @@ ImprovedTube.ytElementsHandler = function (node) { } else if (name === 'YTD-MASTHEAD') { if (!this.elements.masthead) { this.elements.masthead = {start: node.querySelector('#start'), - end: node.querySelector('#end'), - logo: node.querySelector('a#logo') - }; + end: node.querySelector('#end'), + logo: node.querySelector('a#logo') + }; this.improvedtubeYoutubeIcon(); } @@ -136,7 +136,7 @@ ImprovedTube.ytElementsHandler = function (node) { else if (name === 'TP-YT-APP-DRAWER') { if (!this.elements.app_drawer) { this.elements.app_drawer = {start: node.querySelector('div#header'), - logo: node.querySelector('a#logo') + logo: node.querySelector('a#logo') }; this.improvedtubeYoutubeIcon(); @@ -190,9 +190,9 @@ ImprovedTube.ytElementsHandler = function (node) { } } }).observe(ImprovedTube.elements.player_thumbnail, {attributes: true, - attributeFilter: ['style'], - childList: false, - subtree: false + attributeFilter: ['style'], + childList: false, + subtree: false }); } } else if (name === 'YTD-WATCH-FLEXY') { @@ -215,12 +215,12 @@ ImprovedTube.ytElementsHandler = function (node) { } return {width: ImprovedTube.elements.player.offsetWidth, - height: Math.round(ImprovedTube.elements.player.offsetWidth / (16 / 9)) + height: Math.round(ImprovedTube.elements.player.offsetWidth / (16 / 9)) }; } return {width: NaN, // ?? - height: NaN + height: NaN }; }; @@ -273,9 +273,9 @@ ImprovedTube.videoPageUpdate = function () { if (this.storage.track_watched_videos === true && video_id) { ImprovedTube.messages.send({action: 'watched', - type: 'add', - id: video_id, - title: document.title + type: 'add', + id: video_id, + title: document.title }); } @@ -362,30 +362,31 @@ var timeUpdateInterval = null; var noTimeUpdate = null; ImprovedTube.playerOnTimeUpdate = function() { - if (!timeUpdateInterval) { - timeUpdateInterval = setInterval(function() { - if (ImprovedTube.video_src !== this.src) { - ImprovedTube.video_src = this.src; - - if (ImprovedTube.initialVideoUpdateDone !== true) { + var currentTime = Date.now(); + if (!timeUpdateInterval) { + timeUpdateInterval = setInterval(function() { + if (ImprovedTube.video_src !== this.src) { + ImprovedTube.video_src = this.src; + + if (ImprovedTube.initialVideoUpdateDone !== true) { + ImprovedTube.playerQuality(); + } + } else if (ImprovedTube.latestVideoDuration !== this.duration) { + ImprovedTube.latestVideoDuration = this.duration; + ImprovedTube.playerQuality(); } - } else if (ImprovedTube.latestVideoDuration !== this.duration) { - ImprovedTube.latestVideoDuration = this.duration; - - ImprovedTube.playerQuality(); - } - if (ImprovedTube.storage.always_show_progress_bar === true) {ImprovedTube.showProgressBar();} - if (ImprovedTube.storage.player_remaining_duration === true){ImprovedTube.playerRemainingDuration();} - ImprovedTube.played_time += .5; - }, 500); - } - clearInterval(noTimeUpdate); - noTimeUpdate = setTimeout(function() { + if (ImprovedTube.storage.always_show_progress_bar === true) {ImprovedTube.showProgressBar();} + if (ImprovedTube.storage.player_remaining_duration === true){ImprovedTube.playerRemainingDuration();} + ImprovedTube.played_time += .5; + }, 500); + } + clearInterval(noTimeUpdate); + noTimeUpdate = setTimeout(function() { clearInterval(timeUpdateInterval); - timeUpdateInterval = null; - }, 987); + timeUpdateInterval = null; + }, 987); }; ImprovedTube.playerOnLoadedMetadata = function () { @@ -397,8 +398,8 @@ ImprovedTube.playerOnPause = function (event) { if (ImprovedTube.elements.yt_channel_name) { ImprovedTube.messages.send({action: 'analyzer', - name: ImprovedTube.elements.yt_channel_name.__data.tooltipText, - time: ImprovedTube.played_time + name: ImprovedTube.elements.yt_channel_name.__data.tooltipText, + time: ImprovedTube.played_time }); } ImprovedTube.played_time = 0; @@ -411,9 +412,9 @@ ImprovedTube.playerOnEnded = function (event) { ImprovedTube.playlistUpNextAutoplay(event); ImprovedTube.messages.send({action: 'analyzer', - //adding "?" (not a fix) - name: ImprovedTube.elements.yt_channel_name?.__data.tooltipText, - time: ImprovedTube.played_time + //adding "?" (not a fix) + name: ImprovedTube.elements.yt_channel_name?.__data.tooltipText, + time: ImprovedTube.played_time }); ImprovedTube.played_time = 0; @@ -436,9 +437,9 @@ ImprovedTube.onmousedown = function () { var path = event.composedPath(); for (var i = 0, l = path.length; i < l; i++) { if (path[i].className - // && path[i].className.indexOf + // && path[i].className.indexOf && (/html5-(main-video|video-container)|ytp-play-button/.test(path[i].className)) - ) {ImprovedTube.user_interacted = true;} + ) {ImprovedTube.user_interacted = true;} } } } @@ -533,7 +534,7 @@ ImprovedTube.createIconButton = function (options) { path = document.createElementNS('http://www.w3.org/2000/svg', 'path'), type = this.button_icons[options.type]; - for(const attr of type.svg) svg.setAttribute(attr[0], attr[1]); + for(const attr of type.svg) svg.setAttribute(attr[0], attr[1]); for(const attr of type.path) path.setAttribute(attr[0], attr[1]); svg.appendChild(path); @@ -550,7 +551,7 @@ ImprovedTube.createIconButton = function (options) { event.preventDefault(); event.stopPropagation(); options.onclick.apply(this, arguments); - } + } } else { button.onclick = options.onclick; } @@ -577,8 +578,8 @@ ImprovedTube.createPlayerButton = function (options) { tooltip.style.top = rect.top - 8 + 'px'; tooltip.textContent = this.dataset.title; - if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)){ - tooltip.style.zIndex = 10001;} // needed for cinema mode +if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)){ +tooltip.style.zIndex = 10001;} // needed for cinema mode function mouseleave() { tooltip.remove(); diff --git a/js&css/web-accessible/www.youtube.com/appearance.js b/js&css/web-accessible/www.youtube.com/appearance.js index 7abb02242..5fde0b5b7 100644 --- a/js&css/web-accessible/www.youtube.com/appearance.js +++ b/js&css/web-accessible/www.youtube.com/appearance.js @@ -17,7 +17,7 @@ ImprovedTube.descriptionSidebar = function () { yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid = true; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = true; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments_ep = true; - } catch (error) { console.error("tried to move description to the sidebar", error); } + } catch (error) { console.error("tried to move description to the sidebar", error); } }; /*------------------------------------------------------------------------------ PLAYER @@ -27,163 +27,163 @@ ImprovedTube.descriptionSidebar = function () { ------------------------------------------------------------------------------*/ ImprovedTube.playerSize = function () { if (this.storage.player_size === "custom") { - var width = Number(this.storage.custom_player_size_width) || 1280, - height = Number(this.storage.custom_player_size_height) || 720, - style = this.elements.player_size_style || document.createElement("style"); + var width = Number(this.storage.custom_player_size_width) || 1280, + height = Number(this.storage.custom_player_size_height) || 720, + style = this.elements.player_size_style || document.createElement("style"); - style.textContent = ':root {'; - style.textContent += "--it-player-width:" + width + "px;"; - style.textContent += "--it-player-height:" + height + "px;"; - style.textContent += "}"; + style.textContent = ':root {'; + style.textContent += "--it-player-width:" + width + "px;"; + style.textContent += "--it-player-height:" + height + "px;"; + style.textContent += "}"; - document.body.appendChild(style); - if (document.documentElement.dataset.pageType === 'video') { window.dispatchEvent(new Event('resize')); } + document.body.appendChild(style); + if (document.documentElement.dataset.pageType === 'video') { window.dispatchEvent(new Event('resize')); } } }; /*------------------------------------------------------------------------------ FORCED THEATER MODE ------------------------------------------------------------------------------*/ ImprovedTube.forcedTheaterMode = function () { - if (ImprovedTube.storage.forced_theater_mode === true && ImprovedTube.elements.ytd_watch && ImprovedTube.elements.player) { - var button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); - if (button && ImprovedTube.elements.ytd_watch.theater === false) { - document.cookie = "wide=1;domain=.youtube.com"; - // ImprovedTube.elements.ytd_watch.theater = true; - setTimeout(function () { - button.click(); - }, 100); - } - } + if (ImprovedTube.storage.forced_theater_mode === true && ImprovedTube.elements.ytd_watch && ImprovedTube.elements.player) { + var button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); + if (button && ImprovedTube.elements.ytd_watch.theater === false) { + document.cookie = "wide=1;domain=.youtube.com"; + // ImprovedTube.elements.ytd_watch.theater = true; + setTimeout(function () { + button.click(); + }, 100); + } + } }; /*------------------------------------------------------------------------------ HD THUMBNAIL ------------------------------------------------------------------------------*/ ImprovedTube.playerHdThumbnail = function () { - if (this.storage.player_hd_thumbnail === true) { - var thumbnail = ImprovedTube.elements.player_thumbnail; + if (this.storage.player_hd_thumbnail === true) { + var thumbnail = ImprovedTube.elements.player_thumbnail; - if (thumbnail.style.backgroundImage.indexOf("/hqdefault.jpg") !== -1) { - thumbnail.style.backgroundImage = thumbnail.style.backgroundImage.replace("/hqdefault.jpg", "/maxresdefault.jpg"); - } - } + if (thumbnail.style.backgroundImage.indexOf("/hqdefault.jpg") !== -1) { + thumbnail.style.backgroundImage = thumbnail.style.backgroundImage.replace("/hqdefault.jpg", "/maxresdefault.jpg"); + } + } }; /*------------------------------------------------------------------------------ ALWAYS SHOW PROGRESS BAR ------------------------------------------------------------------------------*/ ImprovedTube.showProgressBar = function () { - var player = ImprovedTube.elements.player; - - if (player && player.className.indexOf("ytp-autohide") !== -1) { - var played = (player.getCurrentTime() * 100) / player.getDuration(), - loaded = player.getVideoBytesLoaded() * 100, - play_bars = player.querySelectorAll(".ytp-play-progress"), - load_bars = player.querySelectorAll(".ytp-load-progress"), - width = 0, - progress_play = 0, - progress_load = 0; - - for (var i = 0, l = play_bars.length; i < l; i++) { - width += play_bars[i].offsetWidth; - } + var player = ImprovedTube.elements.player; + + if (player && player.className.indexOf("ytp-autohide") !== -1) { + var played = (player.getCurrentTime() * 100) / player.getDuration(), + loaded = player.getVideoBytesLoaded() * 100, + play_bars = player.querySelectorAll(".ytp-play-progress"), + load_bars = player.querySelectorAll(".ytp-load-progress"), + width = 0, + progress_play = 0, + progress_load = 0; + + for (var i = 0, l = play_bars.length; i < l; i++) { + width += play_bars[i].offsetWidth; + } - var width_percent = width / 100; + var width_percent = width / 100; - for (var i = 0, l = play_bars.length; i < l; i++) { - var a = play_bars[i].offsetWidth / width_percent, - b = 0, - c = 0; + for (var i = 0, l = play_bars.length; i < l; i++) { + var a = play_bars[i].offsetWidth / width_percent, + b = 0, + c = 0; - if (played - progress_play >= a) { - b = 100; - } else if (played > progress_play && played < a + progress_play) { - b = (100 * ((played - progress_play) * width_percent)) / play_bars[i].offsetWidth; - } + if (played - progress_play >= a) { + b = 100; + } else if (played > progress_play && played < a + progress_play) { + b = (100 * ((played - progress_play) * width_percent)) / play_bars[i].offsetWidth; + } - play_bars[i].style.transform = "scaleX(" + b / 100 + ")"; + play_bars[i].style.transform = "scaleX(" + b / 100 + ")"; - if (loaded - progress_load >= a) { - c = 100; - } else if (loaded > progress_load && loaded < a + progress_load) { - c = (100 * ((loaded - progress_load) * width_percent)) / play_bars[i].offsetWidth; - } + if (loaded - progress_load >= a) { + c = 100; + } else if (loaded > progress_load && loaded < a + progress_load) { + c = (100 * ((loaded - progress_load) * width_percent)) / play_bars[i].offsetWidth; + } - load_bars[i].style.transform = "scaleX(" + c / 100 + ")"; + load_bars[i].style.transform = "scaleX(" + c / 100 + ")"; - progress_play += a; - progress_load += a; - } - } + progress_play += a; + progress_load += a; + } + } }; /*------------------------------------------------------------------------------ VIDEO REMAINING DURATION ------------------------------------------------------------------------------*/ ImprovedTube.formatSecond = function (rTime) { - var time = new Date(null); - if (this.storage.duration_with_speed === true) { - var playbackRate = this.elements.video.playbackRate; - time.setSeconds(rTime / playbackRate); - } else { - time.setSeconds(rTime); - } - - if (rTime / 3600 < 1) { - return time.toISOString().substr(14, 5); - } else { - return time.toISOString().substr(11, 8); - } + var time = new Date(null); + if (this.storage.duration_with_speed === true) { + var playbackRate = this.elements.video.playbackRate; + time.setSeconds(rTime / playbackRate); + } else { + time.setSeconds(rTime); + } + + if (rTime / 3600 < 1) { + return time.toISOString().substr(14, 5); + } else { + return time.toISOString().substr(11, 8); + } }; ImprovedTube.playerRemainingDuration = function () { - var player = ImprovedTube.elements.player; - var rTime = ImprovedTube.formatSecond((player.getDuration() - player.getCurrentTime()).toFixed(0)); - var element = document.querySelector(".ytp-time-remaining-duration"); - if (!element) { - var label = document.createElement("span"); - label.textContent = " (-" + rTime + ")"; - label.className = "ytp-time-remaining-duration"; - document.querySelector(".ytp-time-display").appendChild(label); - } else { - element.textContent = " (-" + rTime + ")"; - } + var player = ImprovedTube.elements.player; + var rTime = ImprovedTube.formatSecond((player.getDuration() - player.getCurrentTime()).toFixed(0)); + var element = document.querySelector(".ytp-time-remaining-duration"); + if (!element) { + var label = document.createElement("span"); + label.textContent = " (-" + rTime + ")"; + label.className = "ytp-time-remaining-duration"; + document.querySelector(".ytp-time-display").appendChild(label); + } else { + element.textContent = " (-" + rTime + ")"; + } }; /*------------------------------------------------------------------------------ Comments Sidebar Simple ------------------------------------------------------------------------------*/ ImprovedTube.commentsSidebarSimple = function() { if(ImprovedTube.storage.comments_sidebar_simple === true){ - if(window.matchMedia("(min-width: 1599px)").matches) { - document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments"));} - if(window.matchMedia("(max-width: 1598px)").matches) { - document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); - setTimeout(function () { - document.querySelector("#primary-inner").appendChild(document.querySelector("#related"));} - );} -} + if(window.matchMedia("(min-width: 1599px)").matches) { + document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments"));} + if(window.matchMedia("(max-width: 1598px)").matches) { + document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); + setTimeout(function () { + document.querySelector("#primary-inner").appendChild(document.querySelector("#related"));} + );} + } } /*------------------------------------------------------------------------------ Comments Sidebar ------------------------------------------------------------------------------*/ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sidebar === true){ - const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); + const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); let hasApplied = 0; - if(/watch\?/.test(location.href)) { - sidebar(); - styleScrollbars(); - setGrid(); - applyObserver(); - window.addEventListener("resize", sidebar) - } + if(/watch\?/.test(location.href)) { + sidebar(); + styleScrollbars(); + setGrid(); + applyObserver(); + window.addEventListener("resize", sidebar) + } function sidebar(){ - resizePlayer(); + resizePlayer(); if(window.matchMedia("(min-width: 1952px)").matches) { if (!hasApplied) { - initialSetup() - setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) + initialSetup() + setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) } else if (hasApplied == 2){ //from medium to big size - setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) + setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) } hasApplied = 1 } @@ -192,21 +192,21 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid initialSetup(); } else if (hasApplied == 1){ //from big to medium - document.getElementById("primary-inner").appendChild(document.getElementById("related")); + document.getElementById("primary-inner").appendChild(document.getElementById("related")); } hasApplied = 2 } else { /// <1000 if(hasApplied == 1){ - document.getElementById("primary-inner").appendChild(document.getElementById("related")); - let comments = document.querySelector("#comments"); - let below = document.getElementById("below"); - below.appendChild(comments); + document.getElementById("primary-inner").appendChild(document.getElementById("related")); + let comments = document.querySelector("#comments"); + let below = document.getElementById("below"); + below.appendChild(comments); } else if (hasApplied == 2){ - let comments = document.querySelector("#comments"); - let below = document.getElementById("below"); - below.appendChild(comments); + let comments = document.querySelector("#comments"); + let below = document.getElementById("below"); + below.appendChild(comments); } hasApplied = 0; } @@ -215,39 +215,39 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid let checkParentInterval = setInterval(() => { container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; if (container) { - clearInterval(checkParentInterval); - container.style.display = "flex"; - container.style.flexWrap = "wrap"; - container.style.flexDirection = "row"; + clearInterval(checkParentInterval); + container.style.display = "flex"; + container.style.flexWrap = "wrap"; + container.style.flexDirection = "row"; } }, 250); } - function initialSetup() { - let secondaryInner = document.getElementById("secondary-inner"); - let primaryInner = document.getElementById("primary-inner"); - let comments = document.querySelector("#comments"); - setTimeout(() => { - primaryInner.appendChild(document.getElementById("panels")); - primaryInner.appendChild(document.getElementById("related")) - secondaryInner.appendChild(document.getElementById("chat-template")); - secondaryInner.appendChild(comments); - }) - } - function resizePlayer() { - const width = video.offsetWidth + 24; - const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); - document.getElementById("primary").style.width = `${width}px`; - player.style.width = `${width}px`; - } - function styleScrollbars(){ - if (!navigator.userAgent.toLowerCase().includes("mac")){ - let color, colorHover - const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; - if(isDarkMode) [color,colorHover] = ["#616161", "#909090"]; - else [color,colorHover] = ["#aaaaaa", "#717171"]; - const style = document.createElement("style"); + function initialSetup() { + let secondaryInner = document.getElementById("secondary-inner"); + let primaryInner = document.getElementById("primary-inner"); + let comments = document.querySelector("#comments"); + setTimeout(() => { + primaryInner.appendChild(document.getElementById("panels")); + primaryInner.appendChild(document.getElementById("related")) + secondaryInner.appendChild(document.getElementById("chat-template")); + secondaryInner.appendChild(comments); + }) + } + function resizePlayer() { + const width = video.offsetWidth + 24; + const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); + document.getElementById("primary").style.width = `${width}px`; + player.style.width = `${width}px`; + } + function styleScrollbars(){ + if (!navigator.userAgent.toLowerCase().includes("mac")){ + let color, colorHover + const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; + if(isDarkMode) [color,colorHover] = ["#616161", "#909090"]; + else [color,colorHover] = ["#aaaaaa", "#717171"]; + const style = document.createElement("style"); if(ImprovedTube.storage.comments_sidebar_scrollbars === true){ - const cssRule = ` + const cssRule = ` #primary, #secondary { overflow: overlay !important; } @@ -268,7 +268,7 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid ::-webkit-scrollbar-thumb:hover{ background-color: ${colorHover}; }`; - style.appendChild(document.createTextNode(cssRule)); + style.appendChild(document.createTextNode(cssRule)); } else { const cssRule = ` #primary, #secondary { @@ -281,24 +281,24 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid }`; style.appendChild(document.createTextNode(cssRule)); } - document.head.appendChild(style); - } - } - function applyObserver(){ - const debouncedResizePlayer = debounce(resizePlayer, 200); - const resizeObserver = new ResizeObserver(debouncedResizePlayer); - resizeObserver.observe(video); - } - function debounce(callback, delay) { - let timerId; - return function (...args) { - clearTimeout(timerId); - timerId = setTimeout(() => { - callback.apply(this, args); - }, delay); - }; - } -} + document.head.appendChild(style); + } + } + function applyObserver(){ + const debouncedResizePlayer = debounce(resizePlayer, 200); + const resizeObserver = new ResizeObserver(debouncedResizePlayer); + resizeObserver.observe(video); + } + function debounce(callback, delay) { + let timerId; + return function (...args) { + clearTimeout(timerId); + timerId = setTimeout(() => { + callback.apply(this, args); + }, delay); + }; + } + } } /*------------------------------------------------------------------------------ SIDEBAR @@ -307,23 +307,23 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid TRANSCRIPT --------------------------------------------------------------*/ ImprovedTube.transcript = function (el){ if (ImprovedTube.storage.transcript === true){ - el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility');} } +el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility');} } /*---------------------------------------------------------------- CHAPTERS --------------------------------------------------------------*/ ImprovedTube.chapters = function (el){ if (ImprovedTube.storage.chapters === true){ - el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility');} } +el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility');} } /*------------------------------------------------------------------------------ LIVECHAT ------------------------------------------------------------------------------*/ ImprovedTube.livechat = function () { - if (this.storage.livechat === "collapsed") { - if (typeof isCollapsed === 'undefined') { var isCollapsed = false; } - if(ImprovedTube.elements.livechat && !isCollapsed){ - ImprovedTube.elements.livechat.button.click(); - isCollapsed = true - } - } /* else{ + if (this.storage.livechat === "collapsed") { + if (typeof isCollapsed === 'undefined') { var isCollapsed = false; } + if(ImprovedTube.elements.livechat && !isCollapsed){ + ImprovedTube.elements.livechat.button.click(); + isCollapsed = true + } + } /* else{ if(isCollapsed){ ImprovedTube.elements.livechat.button.click(); isCollapsed = false @@ -340,101 +340,100 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { if (window.self !== window.top) { return false; } if (document.documentElement.dataset.pageType === 'video') { - var section = document.querySelector('#subscribe-button'); + var section = document.querySelector('#subscribe-button'); /* if (this.storage.description == "classic" || this.storage.description == "classic_expanded" || this.storage.description == "classic_hidden" ) {var section = document.querySelector('#flex.ytd-video-primary-info-renderer');} */ - if (section && !section.querySelector('.improvedtube-player-button')) { - var button, svg, path; - if (this.storage.below_player_loop !== false) { - button = document.createElement('button'); - svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + if (section && !section.querySelector('.improvedtube-player-button')) { + if (this.storage.below_player_loop !== false) { + var button = document.createElement('button'), + svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); var transparentOrOn = .5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } - button.className = 'improvedtube-player-button'; - button.id = 'it-below-player-loop'; - button.dataset.tooltip = 'Loop'; - svg.style.opacity = transparentOrOn; - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z'); - - button.onclick = function () { - var video = ImprovedTube.elements.video, - svg = this.children[0]; - - function matchLoopState(opacity) { + button.className = 'improvedtube-player-button'; + button.id = 'it-below-player-loop'; + button.dataset.tooltip = 'Loop'; + svg.style.opacity = transparentOrOn; + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z'); + + button.onclick = function () { + var video = ImprovedTube.elements.video, + svg = this.children[0]; + + function matchLoopState(opacity) { svg.style.opacity = opacity; - if (ImprovedTube.storage.player_repeat_button === true) { + if (ImprovedTube.storage.player_repeat_button === true) { var otherButton = document.querySelector('#it-repeat-button'); otherButton.style.opacity = opacity; } } - if (video.hasAttribute('loop')) { - video.removeAttribute('loop'); - matchLoopState('.5') - } else if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { - video.setAttribute('loop', ''); - matchLoopState('1') - } - }; + if (video.hasAttribute('loop')) { + video.removeAttribute('loop'); + matchLoopState('.5') + } else if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { + video.setAttribute('loop', ''); + matchLoopState('1') + } + }; - svg.appendChild(path); button.appendChild(svg); - section.insertAdjacentElement('afterend', button) - } + svg.appendChild(path); button.appendChild(svg); + section.insertAdjacentElement('afterend', button) + } if (this.storage.below_player_pip !== false) { - button = document.createElement('button'); - svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + var button = document.createElement('button'), + svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - button.className = 'improvedtube-player-button'; - button.dataset.tooltip = 'PiP'; - svg.style.opacity = '.64'; - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - path.setAttributeNS(null, 'd', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z'); + button.className = 'improvedtube-player-button'; + button.dataset.tooltip = 'PiP'; + svg.style.opacity = '.64'; + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + path.setAttributeNS(null, 'd', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z'); - button.onclick = function () { - var video = document.querySelector('#movie_player video'); - if (video) {video.requestPictureInPicture();} - }; + button.onclick = function () { + var video = document.querySelector('#movie_player video'); + if (video) {video.requestPictureInPicture();} + }; - svg.appendChild(path); button.appendChild(svg); - section.insertAdjacentElement('afterend', button) - } + svg.appendChild(path); button.appendChild(svg); + section.insertAdjacentElement('afterend', button) + } if (this.storage.below_player_screenshot !== false) { - button = document.createElement('button'); - svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + var button = document.createElement('button'), + svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - button.className = 'improvedtube-player-button'; - button.dataset.tooltip = 'Screenshot'; - svg.style.opacity = '.55'; - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - path.setAttributeNS(null, 'd', 'M21 19V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z'); + button.className = 'improvedtube-player-button'; + button.dataset.tooltip = 'Screenshot'; + svg.style.opacity = '.55'; + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + path.setAttributeNS(null, 'd', 'M21 19V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z'); - button.onclick = ImprovedTube.screenshot; + button.onclick = ImprovedTube.screenshot; - svg.appendChild(path); button.appendChild(svg); - section.insertAdjacentElement('afterend', button) - } + svg.appendChild(path); button.appendChild(svg); + section.insertAdjacentElement('afterend', button) + } } - } + } }; /*------------------------------------------------------------------------------ EXPAND DESCRIPTION ------------------------------------------------------------------------------*/ ImprovedTube.expandDescription = function (el) { - if (this.storage.description === "expanded" || this.storage.description === "classic_expanded") { - if (el) {el.click(); setTimeout(function(){ImprovedTube.elements.player.focus();}, 1200); } - else { var tries = 0; var intervalMs = 210; var maxTries; if (location.href.indexOf('/watch?') !== -1) {maxTries = 10;} else {maxTries = 0;} - // ...except when it is an embedded player? - var waitForDescription = setInterval(() => { - if (++tries >= maxTries) { + if (this.storage.description === "expanded" || this.storage.description === "classic_expanded") { + if (el) {el.click(); setTimeout(function(){ImprovedTube.elements.player.focus();}, 1200); } + else { var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} + // ...except when it is an embedded player? + var waitForDescription = setInterval(() => { + if (++tries >= maxTries) { el = document.querySelector('#description-inline-expander') if ( el) { el.click(); setTimeout(function(){ImprovedTube.elements.player.focus(); }, 1200);clearInterval(waitForDescription); } intervalMs *= 1.11; }}, intervalMs); - } + } } } /*------------------------------------------------------------------------------ @@ -455,180 +454,180 @@ ImprovedTube.expandDescription = function (el) { DAY OF WEEK --------------------------------------------------------------*/ ImprovedTube.dayOfWeek = function () { if (this.storage.day_of_week === true) { - var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; - setTimeout(function () { - var videoDate; try { videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate } //YouTube related video or internal link? - catch { try { videoDate = document.querySelector("[itemprop=datePublished]").content;} catch { } } //..no? must be new session? - var tempDate = new Date(videoDate); - var element = document.querySelector(".ytd-day-of-week"); - if (!element) { - var label = document.createElement("span"); - label.textContent = days[tempDate.getDay() + 1] + ' '; - label.className = "ytd-day-of-week"; - //update please: - try {document.querySelector("#info span:nth-child(2)")?.append(label);} catch { try {document.querySelector("#info #info-strings yt-formatted-string")?.append(label);}catch {}} - } // else { element.textContent = days[tempDate.getDay() + 1] + ", "; } - }, 4321); -} + var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; + setTimeout(function () { + var videoDate; try { videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate } //YouTube related video or internal link? + catch { try { videoDate = document.querySelector("[itemprop=datePublished]").content;} catch { } } //..no? must be new session? + var tempDate = new Date(videoDate); + var element = document.querySelector(".ytd-day-of-week"); + if (!element) { + var label = document.createElement("span"); + label.textContent = days[tempDate.getDay() + 1] + ' '; + label.className = "ytd-day-of-week"; + //update please: + try {document.querySelector("#info span:nth-child(2)")?.append(label);} catch { try {document.querySelector("#info #info-strings yt-formatted-string")?.append(label);}catch {}} + } // else { element.textContent = days[tempDate.getDay() + 1] + ", "; } + }, 4321); + } }; /*------------------------------------------------------------------------------ HOW LONG AGO THE VIDEO WAS UPLOADED ------------------------------------------------------------------------------*/ ImprovedTube.howLongAgoTheVideoWasUploaded = function () { - if (this.storage.how_long_ago_the_video_was_uploaded === true && this.elements.yt_channel_name) { - var xhr = new XMLHttpRequest(), - key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey, - id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); + if (this.storage.how_long_ago_the_video_was_uploaded === true && this.elements.yt_channel_name) { + var xhr = new XMLHttpRequest(), + key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey, + id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); - function timeSince(date) { - var seconds = Math.floor((new Date() - new Date(date)) / 1000), - interval = Math.floor(seconds / 31536000); + function timeSince(date) { + var seconds = Math.floor((new Date() - new Date(date)) / 1000), + interval = Math.floor(seconds / 31536000); - if (interval > 1) { - return interval + " years ago"; - } - interval = Math.floor(seconds / 2592000); - if (interval > 1) { - return interval + " months ago"; - } - interval = Math.floor(seconds / 86400); - if (interval > 1) { - return interval + " days ago"; - } - interval = Math.floor(seconds / 3600); - if (interval > 1) { - return interval + " hours ago"; - } - interval = Math.floor(seconds / 60); - if (interval > 1) { - return interval + " minutes ago"; - } + if (interval > 1) { + return interval + " years ago"; + } + interval = Math.floor(seconds / 2592000); + if (interval > 1) { + return interval + " months ago"; + } + interval = Math.floor(seconds / 86400); + if (interval > 1) { + return interval + " days ago"; + } + interval = Math.floor(seconds / 3600); + if (interval > 1) { + return interval + " hours ago"; + } + interval = Math.floor(seconds / 60); + if (interval > 1) { + return interval + " minutes ago"; + } - return Math.floor(seconds) + " seconds ago"; - } + return Math.floor(seconds) + " seconds ago"; + } - xhr.addEventListener("load", function () { - var response = JSON.parse(this.responseText), - element = ImprovedTube.elements.how_long_ago_the_video_was_uploaded || document.createElement("div"); + xhr.addEventListener("load", function () { + var response = JSON.parse(this.responseText), + element = ImprovedTube.elements.how_long_ago_the_video_was_uploaded || document.createElement("div"); - ImprovedTube.empty(element); + ImprovedTube.empty(element); - if (response.error) { - element.appendChild(document.createTextNode("• Error: " + response.error.code)); - } else { - element.appendChild(document.createTextNode("• " + timeSince(response.items[0].snippet.publishedAt))); - } + if (response.error) { + element.appendChild(document.createTextNode("• Error: " + response.error.code)); + } else { + element.appendChild(document.createTextNode("• " + timeSince(response.items[0].snippet.publishedAt))); + } - element.className = "it-how-long-ago-the-video-was-uploaded"; + element.className = "it-how-long-ago-the-video-was-uploaded"; - ImprovedTube.elements.how_long_ago_the_video_was_uploaded = element; + ImprovedTube.elements.how_long_ago_the_video_was_uploaded = element; - document.querySelector("#info #info-text").appendChild(element); - }); + document.querySelector("#info #info-text").appendChild(element); + }); - xhr.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + id + "&key=" + key, true); - xhr.send(); - } + xhr.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + id + "&key=" + key, true); + xhr.send(); + } }; /*------------------------------------------------------------------------------ SHOW CHANNEL VIDEOS COUNT ------------------------------------------------------------------------------*/ ImprovedTube.channelVideosCount = function () { - if (this.storage.channel_videos_count === true && this.elements.yt_channel_link) { - var key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey; - if (this.elements.yt_channel_link.href.indexOf("/channel/") == -1) { - var xhr = new XMLHttpRequest(), - id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); - xhr.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + id + "&key=" + key, false); - xhr.send(); - if (xhr.readyState === xhr.DONE && xhr.status === 200) { - var response = JSON.parse(xhr.responseText); - id = response.items[0].snippet.channelId; - } - } else { - id = this.elements.yt_channel_link.href.slice(this.elements.yt_channel_link.href.indexOf("/channel/") + "/channel/".length); - if (id.indexOf("/") !== -1) { - id = id.match(/.+?(?=\/)/)[0]; - } - } + if (this.storage.channel_videos_count === true && this.elements.yt_channel_link) { + var key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey; + if (this.elements.yt_channel_link.href.indexOf("/channel/") == -1) { + var xhr = new XMLHttpRequest(), + id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); + xhr.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + id + "&key=" + key, false); + xhr.send(); + if (xhr.readyState === xhr.DONE && xhr.status === 200) { + var response = JSON.parse(xhr.responseText); + id = response.items[0].snippet.channelId; + } + } else { + id = this.elements.yt_channel_link.href.slice(this.elements.yt_channel_link.href.indexOf("/channel/") + "/channel/".length); + if (id.indexOf("/") !== -1) { + id = id.match(/.+?(?=\/)/)[0]; + } + } - xhr = new XMLHttpRequest(); + xhr = new XMLHttpRequest(); - xhr.addEventListener("load", function () { - var response = JSON.parse(this.responseText), - parent = document.querySelector("#meta ytd-channel-name + yt-formatted-string"), - element = ImprovedTube.elements.channel_videos_count || document.createElement("div"); + xhr.addEventListener("load", function () { + var response = JSON.parse(this.responseText), + parent = document.querySelector("#meta ytd-channel-name + yt-formatted-string"), + element = ImprovedTube.elements.channel_videos_count || document.createElement("div"); - ImprovedTube.empty(element); + ImprovedTube.empty(element); - if (response.error) { - element.appendChild(document.createTextNode("• Error: " + response.error.code)); - } else { - element.appendChild(document.createTextNode("• " + response.items[0].statistics.videoCount + " videos")); - } + if (response.error) { + element.appendChild(document.createTextNode("• Error: " + response.error.code)); + } else { + element.appendChild(document.createTextNode("• " + response.items[0].statistics.videoCount + " videos")); + } - element.className = "it-channel-videos-count"; + element.className = "it-channel-videos-count"; - ImprovedTube.elements.channel_videos_count = element; + ImprovedTube.elements.channel_videos_count = element; - parent.appendChild(element); + parent.appendChild(element); - ImprovedTube.elements.channel_videos_count = element; - }); + ImprovedTube.elements.channel_videos_count = element; + }); - xhr.open("GET", "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + id + "&key=" + key, true); - xhr.send(); - } + xhr.open("GET", "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + id + "&key=" + key, true); + xhr.send(); + } }; if (ImprovedTube.storage.header_transparent2 === true) { - /*------------------------------------------------------------------------------ + /*------------------------------------------------------------------------------ TURN TOP BAR TRANSPARENT WHEN SCROLLING ------------------------------------------------------------------------------*/ - window.addEventListener('scroll', function () { - var masthead = document.querySelector('html[it-header-transparent=true] ytd-masthead'); - var endButtons = masthead.querySelector('#end'); - - if (window.scrollY === 0) { - endButtons.style.visibility = 'visible'; - } else { - endButtons.style.visibility = 'hidden'; - } - }); - - function handleScroll() { - var scrollTop = window.pageYOffset || document.documentElement.scrollTop; - var buttonsContainer = document.getElementById('buttons'); - - if (scrollTop > 100) { - buttonsContainer.classList.add('hidden'); - } else { - buttonsContainer.classList.remove('hidden'); - } - } - - /*------------------------------------------------------------------------------ + window.addEventListener('scroll', function () { + var masthead = document.querySelector('html[it-header-transparent=true] ytd-masthead'); + var endButtons = masthead.querySelector('#end'); + + if (window.scrollY === 0) { + endButtons.style.visibility = 'visible'; + } else { + endButtons.style.visibility = 'hidden'; + } + }); + + function handleScroll() { + var scrollTop = window.pageYOffset || document.documentElement.scrollTop; + var buttonsContainer = document.getElementById('buttons'); + + if (scrollTop > 100) { + buttonsContainer.classList.add('hidden'); + } else { + buttonsContainer.classList.remove('hidden'); + } + } + + /*------------------------------------------------------------------------------ CHECK IF USER IS SCROLLING ------------------------------------------------------------------------------*/ - window.addEventListener("scroll", handleScroll); - - function getScrollDirection() { - var lastScrollTop = 0; - return function() { - var st = window.pageYOffset || document.documentElement.scrollTop; - var scrollDirection = st > lastScrollTop ? 'down' : 'up'; - lastScrollTop = st <= 0 ? 0 : st; - return scrollDirection; - }; - } - - var scrollDirection = getScrollDirection(); - - window.addEventListener('scroll', function() { - var direction = scrollDirection(); - if (direction === 'down') { - document.documentElement.setAttribute('data-scroll-direction', 'down'); - } else { - document.documentElement.removeAttribute('data-scroll-direction'); - } - }); + window.addEventListener("scroll", handleScroll); + + function getScrollDirection() { + var lastScrollTop = 0; + return function() { + var st = window.pageYOffset || document.documentElement.scrollTop; + var scrollDirection = st > lastScrollTop ? 'down' : 'up'; + lastScrollTop = st <= 0 ? 0 : st; + return scrollDirection; + }; + } + + var scrollDirection = getScrollDirection(); + + window.addEventListener('scroll', function() { + var direction = scrollDirection(); + if (direction === 'down') { + document.documentElement.setAttribute('data-scroll-direction', 'down'); + } else { + document.documentElement.removeAttribute('data-scroll-direction'); + } + }); } diff --git a/js&css/web-accessible/www.youtube.com/blocklist.js b/js&css/web-accessible/www.youtube.com/blocklist.js index 3b145c6b7..9e61c6c58 100644 --- a/js&css/web-accessible/www.youtube.com/blocklist.js +++ b/js&css/web-accessible/www.youtube.com/blocklist.js @@ -13,7 +13,7 @@ ImprovedTube.blocklistNode = function (node) { // YT reuses Thumbnail cells dynamically, need to monitor all created Thumbnail links and dynamically apply/remove 'it-blocklisted-*' classes if (!this.elements.observerList.includes(node)) { this.blocklistObserver.observe(node, {attributes: true, - attributeFilter: ['href']}); + attributeFilter: ['href']}); // keeping a list to attach only one observer per tracked element this.elements.observerList.push(node); } @@ -77,12 +77,12 @@ ImprovedTube.blocklistNode = function (node) { // this message will trigger 'storage-changed' event and eventually blocklistInit() full rescan ImprovedTube.messages.send({action: 'blocklist', - added: added, - type: type, - id: type == 'channel' ? channel : video, - title: title, - when: Date.parse(new Date().toDateString()) / 100000 - }); + added: added, + type: type, + id: type == 'channel' ? channel : video, + title: title, + when: Date.parse(new Date().toDateString()) / 100000 + }); } }); @@ -128,13 +128,13 @@ ImprovedTube.blocklistChannel = function (node) { // this message will trigger 'storage-changed' event and eventually blocklistInit() full rescan ImprovedTube.messages.send({action: 'blocklist', - added: !ImprovedTube.storage.blocklist.channels[id], - type: 'channel', - id: id, - title: title, - preview: preview, - when: Date.parse(new Date().toDateString()) / 100000 - }); + added: !ImprovedTube.storage.blocklist.channels[id], + type: 'channel', + id: id, + title: title, + preview: preview, + when: Date.parse(new Date().toDateString()) / 100000 + }); }; node.parentNode.parentNode.appendChild(button); @@ -229,38 +229,40 @@ ImprovedTube.blocklistObserver = new MutationObserver(function (mutationList) { ImprovedTube.blocklistElementTypeHelper = function (node) { switch(node.parentNode.className.replace('style-scope ','')) { - case 'ytd-compact-video-renderer': - // list next to player - // node.parentNode.__dataHost.$.dismissible; - case 'ytd-rich-item-renderer': - // short reel - case 'ytd-rich-grid-media': - // grid reel - case 'ytd-rich-grid-slim-media': - // short grid reel - case 'ytd-playlist-video-renderer': - // playlist page - case 'ytd-playlist-panel-video-renderer': - // playlist next to player - // node.parentNode.closest('ytd-playlist-panel-video-renderer') - case 'ytd-structured-description-video-lockup-renderer': - // list under the player - // node.parentNode.closest('ytd-structured-description-video-lockup-renderer') - // or even node.parentNode.closest('ytd-compact-infocard-renderer') === node.parentNode.parentNode.parentNode.parentNode - case 'ytd-video-renderer': - // search results - case 'ytd-video-preview': - // subscriptions/search thumbnail video-preview - return node.parentNode.parentNode.parentNode; + case 'ytd-compact-video-renderer': + // list next to player + // node.parentNode.__dataHost.$.dismissible; + case 'ytd-rich-item-renderer': + // short reel + case 'ytd-rich-grid-media': + // grid reel + case 'ytd-rich-grid-slim-media': + // short grid reel + case 'ytd-playlist-video-renderer': + // playlist page + case 'ytd-playlist-panel-video-renderer': + // playlist next to player + // node.parentNode.closest('ytd-playlist-panel-video-renderer') + case 'ytd-structured-description-video-lockup-renderer': + // list under the player + // node.parentNode.closest('ytd-structured-description-video-lockup-renderer') + // or even node.parentNode.closest('ytd-compact-infocard-renderer') === node.parentNode.parentNode.parentNode.parentNode + case 'ytd-video-renderer': + // search results + case 'ytd-video-preview': + // subscriptions/search thumbnail video-preview + return node.parentNode.parentNode.parentNode; + break; - case 'ytd-grid-video-renderer': - // channel home screen grid - case 'ytd-reel-item-renderer': - // reel - return node.parentNode.parentNode; + case 'ytd-grid-video-renderer': + // channel home screen grid + case 'ytd-reel-item-renderer': + // reel + return node.parentNode.parentNode; + break; - default: - // unknown ones land here - break; + default: + // unknown ones land here + break; } }; diff --git a/js&css/web-accessible/www.youtube.com/channel.js b/js&css/web-accessible/www.youtube.com/channel.js index c470eb943..e4db1aa78 100644 --- a/js&css/web-accessible/www.youtube.com/channel.js +++ b/js&css/web-accessible/www.youtube.com/channel.js @@ -36,11 +36,11 @@ ImprovedTube.channelPlayAllButton = function () { return; } const button = this.createIconButton({ - type: 'playAll', - className: 'it-play-all-button', - text: 'Play all', - href: '/playlist?list=UU' + playlistUrl - }); + type: 'playAll', + className: 'it-play-all-button', + text: 'Play all', + href: '/playlist?list=UU' + playlistUrl + }); container.appendChild(button); } else { document.querySelector('.it-play-all-button')?.remove(); @@ -55,15 +55,15 @@ var compact = compact || {} ImprovedTube.channelCompactTheme = function () { compact.eventHandlerFns = compact.eventHandlerFns || [] compact.styles = compact.styles || [] - if (this.storage.channel_compact_theme === true) { + if (this.storage.channel_compact_theme === true) { compact.hasApplied = true initialLoad(); document.querySelector("#sections #items") ? styleWithListeners() : styleWithInterval(); - } + } else if (compact.hasApplied) { //cleanup try {clearInterval(compact.listener)} catch (err) {console.log("ERR: We couldn't clear listener. Reload page")} - if (compact.eventHandlerFns.length) removeListeners(); + if (compact.eventHandlerFns.length) removeListeners(); if (compact.styles.length) removeStyles() compact = {} } @@ -117,22 +117,22 @@ ImprovedTube.channelCompactTheme = function () { } function initialLoad() { - for (let i = 0; i <= 2; i++) { - let isCompact = localStorage.getItem(`ImprovedTube-compact-${i + 2}`) === "true" + for (let i = 0; i <= 2; i++) { + let isCompact = localStorage.getItem(`ImprovedTube-compact-${i + 2}`) === "true" isCompact ? appendStyle(i) : (compact.styles[i] = null); - } - } + } + } - function appendStyle(index) { // adds style tag - const cssRules = ` + function appendStyle(index) { // adds style tag + const cssRules = ` #sections > ytd-guide-section-renderer:nth-child(${index + 2}) > #items{ display:none; };`; - const style = document.createElement("style"); - style.appendChild(document.createTextNode(cssRules)); - compact.styles[index] = style; - document.head.appendChild(compact.styles[index]); - } + const style = document.createElement("style"); + style.appendChild(document.createTextNode(cssRules)); + compact.styles[index] = style; + document.head.appendChild(compact.styles[index]); + } function removeStyles(){ // styles tags for (let i = 0; i <= compact.styles.length; i++){ diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index e473a5562..0bada3ba5 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -80,7 +80,7 @@ ImprovedTube.playerAutoPip = function () { console.error('Failed to enter Picture-in-Picture mode', error); } })(); - } + } }; /*------------------------------------------------------------------------------ PLAYBACK SPEED @@ -112,52 +112,52 @@ ImprovedTube.playbackSpeed = function (newSpeed) { FORCED PLAYBACK SPEED ------------------------------------------------------------------------------*/ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_playback_speed === true) { - var player = this.elements.player, + var player = this.elements.player, video = player.querySelector('video'), option = this.storage.player_playback_speed; - if (this.isset(option) === false) { option = 1; } - else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) ) + if (this.isset(option) === false) { option = 1; } + else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) ) { console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; } - if ( !player.getVideoData().isLive || player.getVideoData().isLive === false) - { player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl - if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true) + if ( !player.getVideoData().isLive || player.getVideoData().isLive === false) +{ player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl + if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true) && option !== 1) { - ImprovedTube.speedException = function () { - if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education') - {player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return;} - if (this.storage.player_force_speed_on_music === true) - { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); +ImprovedTube.speedException = function () { +if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education') + {player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return;} +if (this.storage.player_force_speed_on_music === true) + { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); return;} - if (DATA.keywords && !keywords) { keywords = DATA.keywords.join(', ') || ''; } - if (keywords === 'video, sharing, camera phone, video phone, free, upload') { keywords = ''; } - var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i; - var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i; - var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i"); - var musicRegexMatch = musicIdentifiersTitle.test(DATA.title); - if (!musicRegexMatch) { - var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i; - var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i"); +if (DATA.keywords && !keywords) { keywords = DATA.keywords.join(', ') || ''; } +if (keywords === 'video, sharing, camera phone, video phone, free, upload') { keywords = ''; } +var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i; +var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i; +var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i"); +var musicRegexMatch = musicIdentifiersTitle.test(DATA.title); + if (!musicRegexMatch) { + var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i; + var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i"); keywordsAmount = 1 + ((keywords || '').match(/,/) || []).length; - if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) { - musicRegexMatch = true}} - notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); - // (Tags/keywords shouldnt lie & very few songs titles might have these words) - if (DATA.duration) { - function parseDuration(duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); - return h * 3600 + m * 60 + s; } - DATA.lengthSeconds = parseDuration(DATA.duration); } - function testSongDuration(s, ytMusic) { - if (135 <= s && s <= 260) {return 'veryCommon';} - if (105 <= s && s <= 420) {return 'common';} - if (420 <= s && s <= 720) {return 'long';} - if (45 <= s && s <= 105) {return 'short';} - if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) {return 'multiple';} + if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) { + musicRegexMatch = true}} +notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); + // (Tags/keywords shouldnt lie & very few songs titles might have these words) + if (DATA.duration) { + function parseDuration(duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); + return h * 3600 + m * 60 + s; } + DATA.lengthSeconds = parseDuration(DATA.duration); } + function testSongDuration(s, ytMusic) { + if (135 <= s && s <= 260) {return 'veryCommon';} + if (105 <= s && s <= 420) {return 'common';} + if (420 <= s && s <= 720) {return 'long';} + if (45 <= s && s <= 105) {return 'short';} + if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) {return 'multiple';} //does Youtube ever show more than 10 songs below the description? } - var songDurationType = testSongDuration(DATA.lengthSeconds); - console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType); - // check if the video is PROBABLY MUSIC: - if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon')) +var songDurationType = testSongDuration(DATA.lengthSeconds); +console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType); + // check if the video is PROBABLY MUSIC: + if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon')) || ( musicRegexMatch && !notMusicRegexMatch && (typeof songDurationType !== 'undefined' || (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords) && 1000 <= DATA.lengthSeconds )) ) // && 1150 <= DATA.lengthSeconds <= 5000 @@ -166,73 +166,73 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ && 1000 <= DATA.lengthSeconds )) ) // && DATA.lengthSeconds <= 5000 || (amountOfSongs && testSongDuration(DATA.lengthSeconds, amountOfSongs ) !== 'undefined') // || location.href.indexOf('music.') !== -1 // (=currently we are only running on www.youtube.com anyways) - ) { player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); } - else { // Now this video might rarely be music + ) { player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); } + else { // Now this video might rarely be music // - however we can make extra-sure after waiting for the video descripion to load... (#1539) - var tries = 0; var intervalMs = 210; var maxTries; if (location.href.indexOf('/watch?') !== -1) {maxTries = 10;} else {maxTries = 0;} - // ...except when it is an embedded player? + var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} + // ...except when it is an embedded player? var waitForDescription = setInterval(() => { - if (++tries >= maxTries) { - subtitle = document.querySelector('#title + #subtitle:last-of-type') - if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs) + if (++tries >= maxTries) { + subtitle = document.querySelector('#title + #subtitle:last-of-type') + if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs) && typeof testSongDuration(DATA.lengthSeconds, Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) ) !== 'undefined' ) // resonable duration {player.setPlaybackRate(1); video.playbackRate = 1; console.log("...but YouTube shows music below the description!"); clearInterval(waitForDescription); } - intervalMs *= 1.11; }}, intervalMs); + intervalMs *= 1.11; }}, intervalMs); window.addEventListener('load', () => { setTimeout(() => { clearInterval(waitForDescription); }, 1234); }); } - } - //DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere) - DATA = {}; - defaultKeywords = "video,sharing,camera,phone,video phone,free,upload"; - DATA.keywords = false; keywords = false; amountOfSongs = false; - DATA.videoID = ImprovedTube.videoId() || false; - ImprovedTube.fetchDOMData = function () { + } +//DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere) +DATA = {}; +defaultKeywords = "video,sharing,camera,phone,video phone,free,upload"; +DATA.keywords = false; keywords = false; amountOfSongs = false; +DATA.videoID = ImprovedTube.videoId() || false; + ImprovedTube.fetchDOMData = function () { // if (history.length > 1 && history.state.endpoint.watchEndpoint) { - try { DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name;} + try { DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name;} catch { DATA.genre = false; DATA.keywords = false; DATA.lengthSeconds = false; - try { - DATA.title = document.getElementsByTagName('meta')?.title?.content || false; - DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; - DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; + try { + DATA.title = document.getElementsByTagName('meta')?.title?.content || false; + DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; + DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; } catch {}} if ( DATA.title === ImprovedTube.videoTitle() ) { keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if(!keywords){keyword=''} ImprovedTube.speedException(); } else { keywords = ''; (async function () { try { const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`); - const htmlContent = await response.text(); - const metaRegex = /]+name=["'](keywords|genre|duration)["'][^>]+content=["']([^"']+)["'][^>]*>/gi; - let match; while ((match = metaRegex.exec(htmlContent)) !== null) { - const [, property, value] = match; - if (property === 'keywords') { keywords = value;} else {DATA[property] = value;} - } - amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false; - if (keywords) { ImprovedTube.speedException(); } - } catch (error) { console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; } - })(); - } - }; - if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { ImprovedTube.fetchDOMData();} - else { - //Invidious instances. Should be updated automatically!... - const invidiousInstances = ['invidious.fdn.fr','inv.tux.pizza','invidious.flokinet.to','invidious.protokolla.fi','invidious.private.coffee','yt.artemislena.eu','invidious.perennialte.ch','invidious.materialio.us','iv.datura.network']; - function getRandomInvidiousInstance() { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} - - (async function () { let retries = 4; let invidiousFetched = false; - async function fetchInvidiousData() { - try {const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); + const htmlContent = await response.text(); + const metaRegex = /]+name=["'](keywords|genre|duration)["'][^>]+content=["']([^"']+)["'][^>]*>/gi; + let match; while ((match = metaRegex.exec(htmlContent)) !== null) { + const [, property, value] = match; + if (property === 'keywords') { keywords = value;} else {DATA[property] = value;} + } + amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false; + if (keywords) { ImprovedTube.speedException(); } + } catch (error) { console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; } + })(); + } + }; +if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { ImprovedTube.fetchDOMData();} +else { +//Invidious instances. Should be updated automatically!... +const invidiousInstances = ['invidious.fdn.fr','inv.tux.pizza','invidious.flokinet.to','invidious.protokolla.fi','invidious.private.coffee','yt.artemislena.eu','invidious.perennialte.ch','invidious.materialio.us','iv.datura.network']; +function getRandomInvidiousInstance() { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} + +(async function () { let retries = 4; let invidiousFetched = false; + async function fetchInvidiousData() { + try {const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); DATA = await response.json(); if (DATA.genre && DATA.title && DATA.keywords && DATA.lengthSeconds) { if (DATA.keywords.toString() === defaultKeywords ) {DATA.keywords = ''} ImprovedTube.speedException(); invidiousFetched = true; } - } catch (error) { console.error('Error: Invidious API: ', error); } - } - while (retries > 0 && !invidiousFetched) { await fetchInvidiousData(); - if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; } } - if(!invidiousFetched){ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} - else { ImprovedTube.fetchDOMData();} } - })(); - } - } // else { } - } + } catch (error) { console.error('Error: Invidious API: ', error); } + } + while (retries > 0 && !invidiousFetched) { await fetchInvidiousData(); + if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; } } + if(!invidiousFetched){ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} + else { ImprovedTube.fetchDOMData();} } +})(); } + } // else { } + } + } } /*------------------------------------------------------------------------------ SUBTITLES @@ -242,14 +242,14 @@ ImprovedTube.playerSubtitles = function () { if (player && player.isSubtitlesOn && player.toggleSubtitles && player.toggleSubtitlesOn) { switch(this.storage.player_subtitles) { - case true: - case 'enabled': - player.toggleSubtitlesOn(); - break - - case 'disabled': - if (player.isSubtitlesOn()) { player.toggleSubtitles(); } - break + case true: + case 'enabled': + player.toggleSubtitlesOn(); + break + + case 'disabled': + if (player.isSubtitlesOn()) { player.toggleSubtitles(); } + break } } }; @@ -313,28 +313,28 @@ ImprovedTube.subtitlesUserSettings = function () { let ytSettings = player.getSubtitlesUserSettings(), setting; - if (!ytSettings) return; //null SubtitlesUserSettings seem to mean subtitles not available + if (!ytSettings) return; //null SubtitlesUserSettings seem to mean subtitles not available for (const value of userSettings) { setting = null; switch(value) { - case 'fontFamily': - case 'fontSizeIncrement': - case 'charEdgeStyle': - setting = Number(ourSettings[value]); - break; - - case 'color': - case 'background': - case 'windowColor': - setting = ourSettings[value]; - break; - - case 'backgroundOpacity': - case 'windowOpacity': - case 'textOpacity': - setting = Number(ourSettings[value]) / 100; - break; + case 'fontFamily': + case 'fontSizeIncrement': + case 'charEdgeStyle': + setting = Number(ourSettings[value]); + break; + + case 'color': + case 'background': + case 'windowColor': + setting = ourSettings[value]; + break; + + case 'backgroundOpacity': + case 'windowOpacity': + case 'textOpacity': + setting = Number(ourSettings[value]) / 100; + break; } if (ytSettings?.hasOwnProperty(value)) { @@ -480,7 +480,7 @@ ImprovedTube.playerQualityWithoutFocus = function () { BATTERY FEATURES; PLAYER QUALITY BASED ON POWER STATUS ------------------------------------------------------------------------------*/ ImprovedTube.batteryFeatures = async function () { - if (ImprovedTube.storage.qualityWhenRunningOnBattery + if (ImprovedTube.storage.qualityWhenRunningOnBattery || ImprovedTube.storage.pauseWhileIUnplugTheCharger || ImprovedTube.storage.whenBatteryIslowDecreaseQuality) { const updateQuality = async (battery, charging) => { @@ -619,11 +619,11 @@ ImprovedTube.screenshot = function () { 'image/png': blob }) ]) - .then(function () { console.log("ImprovedTube: Screeeeeeenshot tada!"); }) - .catch(function (error) { - console.log('ImprovedTube screenshot: ', error); - alert('ImprovedTube Screenshot to Clipboard error. Details in Debug Console.'); - }); + .then(function () { console.log("ImprovedTube: Screeeeeeenshot tada!"); }) + .catch(function (error) { + console.log('ImprovedTube screenshot: ', error); + alert('ImprovedTube Screenshot to Clipboard error. Details in Debug Console.'); + }); } else { let a = document.createElement('a'); a.href = URL.createObjectURL(blob); @@ -636,27 +636,27 @@ ImprovedTube.screenshot = function () { ImprovedTube.renderSubtitle = function (ctx,captionElements) { if (ctx && captionElements) { - captionElements.forEach(function (captionElement, index) { - var captionText = captionElement.textContent.trim(); - var captionStyles = window.getComputedStyle(captionElement); - - ctx.fillStyle = captionStyles.color; - ctx.font = captionStyles.font; - ctx.textAlign = 'center'; - ctx.textBaseline = 'bottom'; - var txtWidth = ctx.measureText(captionText).width; - var txtHeight = parseFloat(captionStyles.fontSize); - - var xOfset = (ctx.canvas.width - txtWidth) / 2; - - var padding = 5; // Adjust the padding as needed - var yofset = ctx.canvas.height - (captionElements.length - index) * (txtHeight + 2 * padding); - - ctx.fillStyle = captionStyles.backgroundColor; - ctx.fillRect(xOfset - padding, yofset - txtHeight - padding, txtWidth + 2 * padding, txtHeight + 2 * padding); - ctx.fillStyle = captionStyles.color; - ctx.fillText(captionText, xOfset + txtWidth / 2, yofset); - }); + captionElements.forEach(function (captionElement, index) { + var captionText = captionElement.textContent.trim(); + var captionStyles = window.getComputedStyle(captionElement); + + ctx.fillStyle = captionStyles.color; + ctx.font = captionStyles.font; + ctx.textAlign = 'center'; + ctx.textBaseline = 'bottom'; + var txtWidth = ctx.measureText(captionText).width; + var txtHeight = parseFloat(captionStyles.fontSize); + + var xOfset = (ctx.canvas.width - txtWidth) / 2; + + var padding = 5; // Adjust the padding as needed + var yofset = ctx.canvas.height - (captionElements.length - index) * (txtHeight + 2 * padding); + + ctx.fillStyle = captionStyles.backgroundColor; + ctx.fillRect(xOfset - padding, yofset - txtHeight - padding, txtWidth + 2 * padding, txtHeight + 2 * padding); + ctx.fillStyle = captionStyles.color; + ctx.fillText(captionText, xOfset + txtWidth / 2, yofset); + }); } }; @@ -683,10 +683,10 @@ ImprovedTube.playerScreenshotButton = function () { REPEAT -------------------------------------------------------------------------------*/ ImprovedTube.playerRepeat = function () { - setTimeout(function () { - if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { - ImprovedTube.elements.video.setAttribute('loop', ''); - } + setTimeout(function () { + if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { + ImprovedTube.elements.video.setAttribute('loop', ''); + } //ImprovedTube.elements.buttons['it-repeat-styles'].style.opacity = '1'; //old class from version 3.x? that both repeat buttons could have }, 200); } @@ -700,21 +700,21 @@ ImprovedTube.playerRepeatButton = function () { svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z'); svg.appendChild(path); - var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } + var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } this.createPlayerButton({ id: 'it-repeat-button', child: svg, opacity: transparentOrOn, onclick: function () { var video = ImprovedTube.elements.video; - function matchLoopState(opacity) { - var thisButton = document.querySelector('#it-repeat-button'); - thisButton.style.opacity = opacity; - if (ImprovedTube.storage.below_player_loop !== false) { - var otherButton = document.querySelector('#it-below-player-loop'); - otherButton.children[0].style.opacity = opacity; - } - } if (video.hasAttribute('loop')) { + function matchLoopState(opacity) { + var thisButton = document.querySelector('#it-repeat-button'); + thisButton.style.opacity = opacity; + if (ImprovedTube.storage.below_player_loop !== false) { + var otherButton = document.querySelector('#it-below-player-loop'); + otherButton.children[0].style.opacity = opacity; + } + } if (video.hasAttribute('loop')) { video.removeAttribute('loop'); matchLoopState('.5') } else if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { @@ -785,10 +785,10 @@ FIT-TO-WIN BUTTON ------------------------------------------------------------------------------*/ ImprovedTube.playerFitToWinButton = function () { if (this.storage.player_fit_to_win_button === true && (/watch\?/.test(location.href))) { - let tempContainer = document.createElement("div"); - tempContainer.innerHTML = ` + let tempContainer = document.createElement("div"); + tempContainer.innerHTML = ` `; - const svg = tempContainer.firstChild; + const svg = tempContainer.firstChild; this.createPlayerButton({ id: 'it-fit-to-win-player-button', child: svg, @@ -821,7 +821,7 @@ var xpath = function(xpathToExecute){ result.push( nodesSnapshot.snapshotItem(i) ); } return result; -} + } function createOverlay() { var overlay = document.createElement('div'); @@ -835,12 +835,12 @@ function createOverlay() { overlay.style.zIndex = '9999'; overlay.style.display = 'block'; document.body.appendChild(overlay); -} + } ImprovedTube.playerCinemaModeButton = function () { if (this.storage.player_cinema_mode_button && (/watch\?/.test(location.href))) { var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), - path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); // TODO: change path such that cinema mode has its own unique icon @@ -896,25 +896,25 @@ ImprovedTube.playerCinemaModeDisable = function () { ImprovedTube.playerCinemaModeEnable = function () { if (this.storage.player_auto_cinema_mode || this.storage.player_auto_hide_cinema_mode_when_paused) { - if ((/watch\?/.test(location.href))) { - var overlay = document.getElementById('overlay_cinema'); + if ((/watch\?/.test(location.href))) { + var overlay = document.getElementById('overlay_cinema'); - if (this.storage.player_auto_cinema_mode === true && !overlay) { - createOverlay(); - overlay = document.getElementById('overlay_cinema'); - } + if (this.storage.player_auto_cinema_mode === true && !overlay) { + createOverlay(); + overlay = document.getElementById('overlay_cinema'); + } - // console.log(overlay && this.storage.player_auto_hide_cinema_mode_when_paused === true || this.storage.player_auto_cinema_mode === true && overlay) - if (overlay) { - overlay.style.display = 'block' - var player = xpath('//*[@id="movie_player"]/div[1]/video')[0].parentNode.parentNode - player.style.zIndex = 10000; - // console.log(player) - var cinemaModeButton = xpath('//*[@id="it-cinema-mode-button"]')[0] - cinemaModeButton.style.opacity = 1 - } +// console.log(overlay && this.storage.player_auto_hide_cinema_mode_when_paused === true || this.storage.player_auto_cinema_mode === true && overlay) + if (overlay) { + overlay.style.display = 'block' + var player = xpath('//*[@id="movie_player"]/div[1]/video')[0].parentNode.parentNode + player.style.zIndex = 10000; + // console.log(player) + var cinemaModeButton = xpath('//*[@id="it-cinema-mode-button"]')[0] + cinemaModeButton.style.opacity = 1 } } + } } /*------------------------------------------------------------------------------ @@ -934,41 +934,41 @@ ImprovedTube.playerHamburgerButton = function () { if(this.storage.player_hambur } let hamburgerMenu = document.querySelector('.custom-hamburger-menu'); - if (!hamburgerMenu) { - hamburgerMenu = document.createElement('div'); - hamburgerMenu.className = 'custom-hamburger-menu'; - hamburgerMenu.style.position = 'absolute'; - hamburgerMenu.style.right = '0'; - hamburgerMenu.style.marginTop = '8px'; - hamburgerMenu.style.cursor = 'pointer'; - - const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - svg.setAttribute('style', 'width: 32px; height: 32px;'); + if (!hamburgerMenu) { + hamburgerMenu = document.createElement('div'); + hamburgerMenu.className = 'custom-hamburger-menu'; + hamburgerMenu.style.position = 'absolute'; + hamburgerMenu.style.right = '0'; + hamburgerMenu.style.marginTop = '8px'; + hamburgerMenu.style.cursor = 'pointer'; - const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z'); - path.setAttributeNS(null, 'fill', 'white'); + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + svg.setAttribute('style', 'width: 32px; height: 32px;'); - svg.appendChild(path); - hamburgerMenu.appendChild(svg); + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z'); + path.setAttributeNS(null, 'fill', 'white'); - controlsContainer.style.paddingRight = '40px'; - controlsContainer.parentNode.appendChild(hamburgerMenu); + svg.appendChild(path); + hamburgerMenu.appendChild(svg); - let controlsVisible = true; - controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; - controlsVisible = false; - - hamburgerMenu.addEventListener('click', function () { + controlsContainer.style.paddingRight = '40px'; + controlsContainer.parentNode.appendChild(hamburgerMenu); + + let controlsVisible = true; controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; - controlsVisible = !controlsVisible; + controlsVisible = false; + + hamburgerMenu.addEventListener('click', function () { + controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; + controlsVisible = !controlsVisible; - // Change the opacity of hamburgerMenu based on controls visibility - hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65'; - }); + // Change the opacity of hamburgerMenu based on controls visibility + hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65'; + }); + } } -} }; /*------------------------------------------------------------------------------ POPUP PLAYER @@ -1048,12 +1048,12 @@ ImprovedTube.playerControls = function () { player.onmousemove = (function() { let thread, onmousestop = function() { - if (document.querySelector(".ytp-progress-bar:hover")) { - thread = setTimeout(onmousestop, 1000); - } else { - player.hideControls(); - } - }; + if (document.querySelector(".ytp-progress-bar:hover")) { + thread = setTimeout(onmousestop, 1000); + } else { + player.hideControls(); + } + }; return function() { player.showControls(); diff --git a/js&css/web-accessible/www.youtube.com/playlist.js b/js&css/web-accessible/www.youtube.com/playlist.js index 39b62317b..0a38d37b0 100644 --- a/js&css/web-accessible/www.youtube.com/playlist.js +++ b/js&css/web-accessible/www.youtube.com/playlist.js @@ -10,9 +10,9 @@ ImprovedTube.playlistUpNextAutoplay = function () { if (this.storage.playlist_up && playlistData.currentIndex && playlistData.totalVideos && playlistData.localCurrentIndex) { - playlistData.currentIndex = playlistData.totalVideos; - } -} + playlistData.currentIndex = playlistData.totalVideos; + } + } }; /*------------------------------------------------------------------------------ 4.5.2 REVERSE @@ -95,15 +95,15 @@ ImprovedTube.playlistReverse = function () { ImprovedTube.playlistRepeat = function () { if ( ImprovedTube.storage.playlist_repeat === true ) { setTimeout(function (){ - var option = ImprovedTube.storage.playlist_repeat, - button = document.querySelector("#button.ytd-playlist-loop-button-renderer") || document.querySelector("ytd-playlist-loop-button-renderer button") || document.querySelector("ytd-playlist-loop-button-renderer"); - if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M21') - ) && button.querySelector("#tooltip")?.textContent !== 'Loop video' + var option = ImprovedTube.storage.playlist_repeat, + button = document.querySelector("#button.ytd-playlist-loop-button-renderer") || document.querySelector("ytd-playlist-loop-button-renderer button") || document.querySelector("ytd-playlist-loop-button-renderer"); + if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M21') + ) && button.querySelector("#tooltip")?.textContent !== 'Loop video' && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Loop video' && button.querySelector("#tooltip")?.textContent !== 'Turn off loop' && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Turn off loop' - ) - { button.click(); } + ) + { button.click(); } }, 10000); } }; @@ -116,12 +116,12 @@ ImprovedTube.playlistRepeat = function () { ImprovedTube.playlistShuffle = function () { if ( ImprovedTube.storage.playlist_shuffle === true ) { setTimeout(function (){ - var button = ImprovedTube.elements.playlist.shuffle_button, - option = ImprovedTube.storage.playlist_shuffle; - button = document.querySelector('#playlist-actions #playlist-action-menu ytd-toggle-button-renderer'); - if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M18.1') - ) ) - { button.click(); } + var button = ImprovedTube.elements.playlist.shuffle_button, + option = ImprovedTube.storage.playlist_shuffle; + button = document.querySelector('#playlist-actions #playlist-action-menu ytd-toggle-button-renderer'); + if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M18.1') + ) ) + { button.click(); } }, 10000); } }; @@ -186,10 +186,10 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c let width = ImprovedTube.elements.player.offsetWidth * 0.7 ?? innerWidth * 0.45; let height = ImprovedTube.elements.player.offsetHeight * 0.7 ?? innerHeight * 0.45; if (!ImprovedTube.elements.player) { - shorts = /short/.test(this.parentElement.href); - if ( width / height < 1 ) { vertical = true } else { vertical = false } - if ( !vertical && shorts ){ width = height * 0.6} - if ( vertical && !shorts ){ height = width * 0.6} } + shorts = /short/.test(this.parentElement.href); + if ( width / height < 1 ) { vertical = true } else { vertical = false } + if ( !vertical && shorts ){ width = height * 0.6} + if ( vertical && !shorts ){ height = width * 0.6} } "use strict"; window.open(`${location.protocol}//www.youtube.com/embed/videoseries?autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}&list=${this.dataset.list}`, '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); //~ change focused tab to URL-less popup @@ -226,25 +226,25 @@ ImprovedTube.playlistPopupUpdate = function () { "use strict"; if (this.storage.playlist_popup === true){ - const playlistID = location.search.match(this.regex.playlist_id)?.[1], - playlistIDMini = this.elements.player?.getPlaylistId?.(); - - if (!document.contains(this.elements.buttons['it-popup-playlist-button-playlist'])) { - const playlistShareButton = document.body.querySelector('ytd-app>div#content>ytd-page-manager>ytd-browse>ytd-playlist-header-renderer ytd-button-renderer.ytd-playlist-header-renderer:has(button[title])'); - if (playlistShareButton == null) this.elements.buttons['it-popup-playlist-button-playlist'] = null; - else playlistShareButton.insertAdjacentElement('afterend', this.elements.buttons['it-popup-playlist-button-playlist'] = this.playlistPopupCreateButton(playlistID)); - } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-playlist'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-playlist'].dataset.list = playlistID; - - if (!document.contains(this.elements.buttons['it-popup-playlist-button-mini'])) { - const miniItemButtons = document.body.querySelector('ytd-app>ytd-miniplayer ytd-playlist-panel-renderer div#top-level-buttons-computed'); - if (miniItemButtons == null) this.elements.buttons['it-popup-playlist-button-mini'] = null; - else miniItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-mini'] = this.playlistPopupCreateButton(playlistIDMini, true, true)); - } else if (playlistIDMini != null && this.elements.buttons['it-popup-playlist-button-mini'].dataset.list !== playlistIDMini) this.elements.buttons['it-popup-playlist-button-mini'].dataset.list = playlistIDMini; - try { - if (!document.contains(this.elements.buttons['it-popup-playlist-button-panel'])) { - const panelItemButtons = document.body.querySelector('ytd-app>div#content>ytd-page-manager>ytd-watch-flexy ytd-playlist-panel-renderer div#top-level-buttons-computed'); - if (panelItemButtons == null) this.elements.buttons['it-popup-playlist-button-panel'] = null; - else panelItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-panel'] = this.playlistPopupCreateButton(playlistID, true, true)); - } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-panel'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-panel'].dataset.list = playlistID; - } catch (error) { console.error("Error appending playlist button panel:", error);} - }}; + const playlistID = location.search.match(this.regex.playlist_id)?.[1], + playlistIDMini = this.elements.player?.getPlaylistId?.(); + + if (!document.contains(this.elements.buttons['it-popup-playlist-button-playlist'])) { + const playlistShareButton = document.body.querySelector('ytd-app>div#content>ytd-page-manager>ytd-browse>ytd-playlist-header-renderer ytd-button-renderer.ytd-playlist-header-renderer:has(button[title])'); + if (playlistShareButton == null) this.elements.buttons['it-popup-playlist-button-playlist'] = null; + else playlistShareButton.insertAdjacentElement('afterend', this.elements.buttons['it-popup-playlist-button-playlist'] = this.playlistPopupCreateButton(playlistID)); + } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-playlist'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-playlist'].dataset.list = playlistID; + + if (!document.contains(this.elements.buttons['it-popup-playlist-button-mini'])) { + const miniItemButtons = document.body.querySelector('ytd-app>ytd-miniplayer ytd-playlist-panel-renderer div#top-level-buttons-computed'); + if (miniItemButtons == null) this.elements.buttons['it-popup-playlist-button-mini'] = null; + else miniItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-mini'] = this.playlistPopupCreateButton(playlistIDMini, true, true)); + } else if (playlistIDMini != null && this.elements.buttons['it-popup-playlist-button-mini'].dataset.list !== playlistIDMini) this.elements.buttons['it-popup-playlist-button-mini'].dataset.list = playlistIDMini; +try { + if (!document.contains(this.elements.buttons['it-popup-playlist-button-panel'])) { + const panelItemButtons = document.body.querySelector('ytd-app>div#content>ytd-page-manager>ytd-watch-flexy ytd-playlist-panel-renderer div#top-level-buttons-computed'); + if (panelItemButtons == null) this.elements.buttons['it-popup-playlist-button-panel'] = null; + else panelItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-panel'] = this.playlistPopupCreateButton(playlistID, true, true)); + } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-panel'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-panel'].dataset.list = playlistID; +} catch (error) { console.error("Error appending playlist button panel:", error);} +}}; diff --git a/js&css/web-accessible/www.youtube.com/shortcuts.js b/js&css/web-accessible/www.youtube.com/shortcuts.js index c6aa742a1..a113fd23f 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -108,20 +108,20 @@ ImprovedTube.shortcuts = function () { let potentialShortcut = {}; for (const button of ['alt','ctrl','shift','wheel','keys']) { switch(button) { - case 'alt': - case 'ctrl': - case 'shift': - case 'toggle': - potentialShortcut[button] = keys[button] || false; + case 'alt': + case 'ctrl': + case 'shift': + case 'toggle': + potentialShortcut[button] = keys[button] || false; break - case 'wheel': - potentialShortcut[button] = keys[button] || 0; + case 'wheel': + potentialShortcut[button] = keys[button] || 0; break - case 'keys': - // array of sorted scancodes - potentialShortcut[button] = keys[button] ? Object.keys(keys[button]).map(s=>Number(s)).sort() : []; + case 'keys': + // array of sorted scancodes + potentialShortcut[button] = keys[button] ? Object.keys(keys[button]).map(s=>Number(s)).sort() : []; break } } @@ -421,14 +421,14 @@ ImprovedTube.shortcutActivateCaptions = function () { }; /*------Chapters------*/ ImprovedTube.shortcutChapters = function () { - try{var height = document.querySelector('*[target-id*=chapters]').clientHeight;}catch{} - if (height) {try{document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close")} catch{}} + try{var height = document.querySelector('*[target-id*=chapters]').clientHeight;}catch{} + if (height) {try{document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close")} catch{}} else { try{document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open")} catch{} } }; /*------Transcript------*/ ImprovedTube.shortcutTranscript = function () { - try{var height = document.querySelector('*[target-id*=transcript]').clientHeight;}catch{} - if (height) {try{document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close")} catch{}} + try{var height = document.querySelector('*[target-id*=transcript]').clientHeight;}catch{} + if (height) {try{document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close")} catch{}} else { try{document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open")} catch{} } }; /*------------------------------------------------------------------------------ @@ -445,19 +445,19 @@ ImprovedTube.shortcutDislike = function () { }; /*------Report------*/ ImprovedTube.shortcutReport = function () { - try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); - document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} +try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); + document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} catch{console.log("'...' failed"); setTimeout(function(){try{document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} - catch{console.log("'...' failed2")}},100) } +catch{console.log("'...' failed2")}},100) } - setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} +setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} catch{console.log("report failed");setTimeout(function() {try{document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} - catch{console.log("report failed2");document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}},800); - } - },200); + catch{console.log("report failed2");document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}},800); + } +},200); - setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed"); - setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed2");}},1700)}},700) +setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed"); + setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed2");}},1700)}},700) } /*------------------------------------------------------------------------------ 4.7.24 SUBSCRIBE diff --git a/js&css/web-accessible/www.youtube.com/themes.js b/js&css/web-accessible/www.youtube.com/themes.js index 9201b1809..023e5fa09 100644 --- a/js&css/web-accessible/www.youtube.com/themes.js +++ b/js&css/web-accessible/www.youtube.com/themes.js @@ -3,26 +3,26 @@ ------------------------------------------------------------------------------*/ ImprovedTube.myColors = function () { if (this.storage.theme === 'custom') { - var style = this.elements.my_colors || document.createElement('style'), - primary_color = this.storage.theme_primary_color, - text_color = this.storage.theme_text_color; + var style = this.elements.my_colors || document.createElement('style'), + primary_color = this.storage.theme_primary_color, + text_color = this.storage.theme_text_color; - if (primary_color) { - primary_color = 'rgb(' + primary_color.join(',') + ')'; - } else { - // need better central place for storing default custom profile colors - primary_color = 'rgb(200, 200, 200)'; - } + if (primary_color) { + primary_color = 'rgb(' + primary_color.join(',') + ')'; + } else { + // need better central place for storing default custom profile colors + primary_color = 'rgb(200, 200, 200)'; + } - if (text_color) { - text_color = 'rgb(' + text_color.join(',') + ')'; - } else { - // need better central place for storing default custom profile colors - text_color = 'rgb(25, 25, 25)'; - } + if (text_color) { + text_color = 'rgb(' + text_color.join(',') + ')'; + } else { + // need better central place for storing default custom profile colors + text_color = 'rgb(25, 25, 25)'; + } - style.className = 'it-theme-editor'; - style.textContent = 'html, [dark] {' + + style.className = 'it-theme-editor'; + style.textContent = 'html, [dark] {' + '--yt-swatch-textbox-bg:rgba(19,19,19,1)!important;' + '--yt-swatch-icon-color:rgba(136,136,136,1)!important;' + '--yt-spec-brand-background-primary:rgba(0,0,0, 0.1) !important;' + @@ -70,46 +70,46 @@ ImprovedTube.myColors = function () { 'background-color: var(--yt-spec-base-background)!important;' + '}'; - this.elements.my_colors = style; - document.documentElement.appendChild(style); - document.documentElement.removeAttribute('dark'); - document.querySelector('ytd-masthead')?.removeAttribute('dark'); - document.getElementById('cinematics')?.style.setProperty("display", "none"); - } else { - this.elements.my_colors?.remove(); - } + this.elements.my_colors = style; + document.documentElement.appendChild(style); + document.documentElement.removeAttribute('dark'); + document.querySelector('ytd-masthead')?.removeAttribute('dark'); + document.getElementById('cinematics')?.style.setProperty("display", "none"); + } else { + this.elements.my_colors?.remove(); + } } ImprovedTube.setTheme = function () { switch(this.storage.theme) { - case 'dark': - document.documentElement.setAttribute('dark', ''); - document.querySelector('ytd-masthead')?.setAttribute('dark', ''); - ImprovedTube.setPrefCookieValueByName('f6', 400); - // fall through - case 'black': - document.getElementById('cinematics')?.removeAttribute('style'); - this.elements.my_colors?.remove(); - break + case 'dark': + document.documentElement.setAttribute('dark', ''); + document.querySelector('ytd-masthead')?.setAttribute('dark', ''); + ImprovedTube.setPrefCookieValueByName('f6', 400); + // fall through + case 'black': + document.getElementById('cinematics')?.removeAttribute('style'); + this.elements.my_colors?.remove(); + break - case 'light': - ImprovedTube.messages.send({action: 'set', key: 'theme', value: null}); - ImprovedTube.setPrefCookieValueByName('f6', null); - // fall through - case 'dawn': - case 'sunset': - case 'night': - case 'plain': - case 'desert': - document.documentElement.removeAttribute('dark'); - document.querySelector('ytd-masthead')?.removeAttribute('dark'); - document.getElementById('cinematics')?.style.setProperty('display', 'none'); - this.elements.my_colors?.remove(); - break + case 'light': + ImprovedTube.messages.send({action: 'set', key: 'theme', value: null}); + ImprovedTube.setPrefCookieValueByName('f6', null); + // fall through + case 'dawn': + case 'sunset': + case 'night': + case 'plain': + case 'desert': + document.documentElement.removeAttribute('dark'); + document.querySelector('ytd-masthead')?.removeAttribute('dark'); + document.getElementById('cinematics')?.style.setProperty('display', 'none'); + this.elements.my_colors?.remove(); + break - case 'default': - document.getElementById('cinematics')?.removeAttribute('style'); - this.elements.my_colors?.remove(); - break + case 'default': + document.getElementById('cinematics')?.removeAttribute('style'); + this.elements.my_colors?.remove(); + break } }; diff --git a/menu/index.js b/menu/index.js index 72666d817..4873dd1f0 100644 --- a/menu/index.js +++ b/menu/index.js @@ -7,7 +7,7 @@ --------------------------------------------------------------*/ satus.storage.import(function (items) { var language = items.language; - if (!language || language === 'default') { language = false;} + if (!language || language === 'default') { language = false;} satus.locale.import(language, function () { satus.render(extension.skeleton); diff --git a/menu/satus.js b/menu/satus.js index a6e5d5559..3e229bd70 100644 --- a/menu/satus.js +++ b/menu/satus.js @@ -1055,12 +1055,12 @@ satus.locale.import = function(code, callback, path) { fetch(url) .then(response => response.ok ? response.json() : {}) .then(data => { - for (var key in data) { - if (!satus.locale.data[key]) { - satus.locale.data[key] = data[key].message; - } + for (var key in data) { + if (!satus.locale.data[key]) { + satus.locale.data[key] = data[key].message; } - }) + } + }) .catch(() => {}) .finally(() => successCallback && successCallback()); } @@ -1140,33 +1140,33 @@ satus.components.modal = function(component, skeleton) { component.scrim.addEventListener('click', function() { // this is someone clicking outside of modal dialog switch (skeleton.variant) { - case 'confirm': - if (skeleton.buttons?.cancel) { - // modal.confirm.buttons variant have own closing mechanism, lets try to click cancel button - if (skeleton.buttons.cancel?.rendered?.click && satus.isFunction(skeleton.buttons.cancel.rendered.click)) { - skeleton.buttons.cancel.rendered.click(); + case 'confirm': + if (skeleton.buttons?.cancel) { + // modal.confirm.buttons variant have own closing mechanism, lets try to click cancel button + if (skeleton.buttons.cancel?.rendered?.click && satus.isFunction(skeleton.buttons.cancel.rendered.click)) { + skeleton.buttons.cancel.rendered.click(); + } else { + // cant find cancel button, just force close it + this.parentNode.close(); + } } else { - // cant find cancel button, just force close it + // modal.confirm simplified variant, try optional cancel() then close() + if (skeleton.cancel && satus.isFunction(skeleton.cancel)) { + skeleton.cancel(); + } this.parentNode.close(); } - } else { - // modal.confirm simplified variant, try optional cancel() then close() - if (skeleton.cancel && satus.isFunction(skeleton.cancel)) { - skeleton.cancel(); - } - this.parentNode.close(); - } - break; + break; - case 'vertical-menu': - this.parentNode.close(); - break; + case 'vertical-menu': + this.parentNode.close(); + break; - case 'shortcut': - case 'color-picker': + case 'shortcut': + case 'color-picker': // click cancel button - skeleton.actions.cancel.rendered.click(); - break; + skeleton.actions.cancel.rendered.click(); + break; } }); @@ -2526,23 +2526,23 @@ satus.components.switch = function(component, skeleton) { satus.components.switch.flip = function(val) { switch(val) { - case true: - this.dataset.value = 'true'; - this.storage.value = true; - break; - case false: - this.dataset.value = 'false'; - this.storage.value = false; - break; - case undefined: - if (this.dataset.value === 'true') { - this.dataset.value = 'false'; - this.storage.value = false; - } else { + case true: this.dataset.value = 'true'; this.storage.value = true; - } - break; + break; + case false: + this.dataset.value = 'false'; + this.storage.value = false; + break; + case undefined: + if (this.dataset.value === 'true') { + this.dataset.value = 'false'; + this.storage.value = false; + } else { + this.dataset.value = 'true'; + this.storage.value = true; + } + break; } }; /*-------------------------------------------------------------- diff --git a/menu/skeleton-parts/appearance.js b/menu/skeleton-parts/appearance.js index 26ffae423..5569abafe 100644 --- a/menu/skeleton-parts/appearance.js +++ b/menu/skeleton-parts/appearance.js @@ -9,10 +9,10 @@ # Sidebar --------------------------------------------------------------*/ satus.storage.onchanged((key, value) => { - if (key === "related_videos" && value === "Titles") { - satus.storage.set('relatedVideosPrev', "Titles"); - console.log(satus.storage.get("relatedVideosPrev")); - } + if (key === "related_videos" && value === "Titles") { + satus.storage.set('relatedVideosPrev', "Titles"); + console.log(satus.storage.get("relatedVideosPrev")); + } }); extension.skeleton.main.layers.section.appearance = { component: "button", @@ -460,19 +460,19 @@ extension.skeleton.main.layers.section.appearance.on.click.description = { component: "select", variant: "description", text: "description", - options: [{ - text: "normal", - value: "normal" - }, { - text: "expanded", - value: "expanded" - }, { - text: "sidebar", - value: "sidebar" - }, { - text: "hidden", - value: "hidden" - }/*, { + options: [{ + text: "normal", + value: "normal" + }, { + text: "expanded", + value: "expanded" + }, { + text: "sidebar", + value: "sidebar" + }, { + text: "hidden", + value: "hidden" + }/*, { text: "Classic", value: "classic" }, { @@ -490,233 +490,233 @@ extension.skeleton.main.layers.section.appearance.on.click.hide_detail_button = text: "Buttons", variant: "detailButton", on: { - click: { - component: 'section', - variant: 'card', - extraButtons: { - component: 'section', - variant: 'card', - title: 'ExtraButtons', + click: { + component: 'section', + variant: 'card', + extraButtons: { + component: 'section', + variant: 'card', + title: 'ExtraButtons', - below_player_screenshot: { - component: 'switch', - text: 'screenshot', - value: true - }, - below_player_pip: { - component: 'switch', - text: 'pictureInPicture', - value: true - }, - below_player_loop: { - component: 'switch', - text: 'loop', - value: true - } - }, - youtubeDetailButtons: { - component: "select", - text: "youTubeButtons", - options: [{ - text: "normal", - value: "normal" - }, { - text: 'removeNames', - value: "remove_labels" - }, { - text: 'halfTransparent', - value: "half_transparent" - }, { - text: 'Remove', - value: "remove" - }, { - text: 'TransparentBackground', - value: "transparent_background" - }, { - text: "hide_labels", - value: "hide_labels" - }, { - text: 'removeIcons', - value: "remove_icons" - }], - tags: "hide,remove" - }, - detailButtons: { - component: 'section', - variant: 'card', - purchase: { - component: "select", - text: "purchase", - options: [{ - text: "normal", - value: "normal" - }, { - text: "removeName", - value: "remove_label" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove,purchase-button" - }, - join: { - component: "select", - text: "join", - options: [{ - text: "normal", - value: "normal" - }, { - text: "removeName", - value: "remove_label" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove,join-button" - }, - subscribe: { - component: "select", - text: "subscribe", - options: [{ - text: "normal", - value: "normal" - }, { - text: "removeName", - value: "remove_label" - }, { - text: "grey", - value: "grey" - }, { - text: "transparentColor", - value: "transparent" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove,subscribe-button" - }, - likes: { - component: "select", - text: "like", - options: [{ - text: "normal", - value: "normal" - }, { - text: "iconsOnly", - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_dislike_button: { - component: "select", - text: "dislike", - options: [{ - text: 'normal', - value: "normal" - }, { - text: 'iconsOnly', - value: "icons_only" - }, { - text: 'hidden', - value: "hidden" - }], - tags: "hide,remove" - }, - red_dislike_button: { - component: 'switch', - text: "redDislikeButton" - }, - hide_share_button: { - component: "select", - text: "share", - options: [{ - text: "normal", - value: "normal" - }, { - text: "iconsOnly", - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_download_button: { - component: "select", - text: 'Download', - options: [{ - text: "normal", - value: "normal" - }, { - text: "iconsOnly", - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_thanks_button: { - component: "select", - text: 'thanks', - options: [{ - text: 'normal', - value: "normal" - }, { - text: 'iconsOnly', - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_clip_button: { - component: "select", - text: 'clip', - options: [{ - text: 'normal', - value: "normal" - }, { - text: 'iconsOnly', - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_save_button: { - component: "select", - text: 'save', - options: [{ - text: 'normal', - value: "normal" - }, { - text: 'iconsOnly', - value: "icons_only" - }, { - text: 'hidden', - value: "hidden" - }], - tags: "hide,remove" - }, - hide_report_button: { - component: "switch", - text: 'hideReport', - tags: "hide,remove" - }, - hide_more_button: { - component: "switch", - text: 'hideMore', - tags: "hide,remove" - } - } + below_player_screenshot: { + component: 'switch', + text: 'screenshot', + value: true + }, + below_player_pip: { + component: 'switch', + text: 'pictureInPicture', + value: true + }, + below_player_loop: { + component: 'switch', + text: 'loop', + value: true + } + }, + youtubeDetailButtons: { + component: "select", + text: "youTubeButtons", + options: [{ + text: "normal", + value: "normal" + }, { + text: 'removeNames', + value: "remove_labels" + }, { + text: 'halfTransparent', + value: "half_transparent" + }, { + text: 'Remove', + value: "remove" + }, { + text: 'TransparentBackground', + value: "transparent_background" + }, { + text: "hide_labels", + value: "hide_labels" + }, { + text: 'removeIcons', + value: "remove_icons" + }], + tags: "hide,remove" + }, + detailButtons: { + component: 'section', + variant: 'card', + purchase: { + component: "select", + text: "purchase", + options: [{ + text: "normal", + value: "normal" + }, { + text: "removeName", + value: "remove_label" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove,purchase-button" + }, + join: { + component: "select", + text: "join", + options: [{ + text: "normal", + value: "normal" + }, { + text: "removeName", + value: "remove_label" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove,join-button" + }, + subscribe: { + component: "select", + text: "subscribe", + options: [{ + text: "normal", + value: "normal" + }, { + text: "removeName", + value: "remove_label" + }, { + text: "grey", + value: "grey" + }, { + text: "transparentColor", + value: "transparent" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove,subscribe-button" + }, + likes: { + component: "select", + text: "like", + options: [{ + text: "normal", + value: "normal" + }, { + text: "iconsOnly", + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_dislike_button: { + component: "select", + text: "dislike", + options: [{ + text: 'normal', + value: "normal" + }, { + text: 'iconsOnly', + value: "icons_only" + }, { + text: 'hidden', + value: "hidden" + }], + tags: "hide,remove" + }, + red_dislike_button: { + component: 'switch', + text: "redDislikeButton" + }, + hide_share_button: { + component: "select", + text: "share", + options: [{ + text: "normal", + value: "normal" + }, { + text: "iconsOnly", + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_download_button: { + component: "select", + text: 'Download', + options: [{ + text: "normal", + value: "normal" + }, { + text: "iconsOnly", + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_thanks_button: { + component: "select", + text: 'thanks', + options: [{ + text: 'normal', + value: "normal" + }, { + text: 'iconsOnly', + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_clip_button: { + component: "select", + text: 'clip', + options: [{ + text: 'normal', + value: "normal" + }, { + text: 'iconsOnly', + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_save_button: { + component: "select", + text: 'save', + options: [{ + text: 'normal', + value: "normal" + }, { + text: 'iconsOnly', + value: "icons_only" + }, { + text: 'hidden', + value: "hidden" + }], + tags: "hide,remove" + }, + hide_report_button: { + component: "switch", + text: 'hideReport', + tags: "hide,remove" + }, + hide_more_button: { + component: "switch", + text: 'hideMore', + tags: "hide,remove" + } + } + } } - } } @@ -840,12 +840,12 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { on: { click: function () { setTimeout(() => { - if (satus.storage.get('related_videos')==="Titles" + if (satus.storage.get('related_videos')==="Titles" && satus.storage.get("relatedVideosPrev") ==="Titles") {if (!satus.storage.get('thumbnails_right')) { this.nextSibling.nextSibling.click(); satus.storage.set('relatedVideosPrev', "notTitles") - } - } + } + } }, 650) } diff --git a/menu/skeleton-parts/blocklist.js b/menu/skeleton-parts/blocklist.js index 259404c5b..d18a7f9be 100644 --- a/menu/skeleton-parts/blocklist.js +++ b/menu/skeleton-parts/blocklist.js @@ -107,10 +107,10 @@ extension.skeleton.main.layers.section.blocklist = { let blocklist = satus.storage.get('blocklist'); if (blocklist && blocklist.channels && Object.keys(blocklist.channels).length) { - this.textContent = '('+Object.keys(blocklist.channels).length+')'; - } else { - this.textContent = '(empty)'; - } + this.textContent = '('+Object.keys(blocklist.channels).length+')'; + } else { + this.textContent = '(empty)'; + } } } } @@ -205,10 +205,10 @@ extension.skeleton.main.layers.section.blocklist = { let blocklist = satus.storage.get('blocklist'); if (blocklist && blocklist.videos && Object.keys(blocklist.videos).length) { - this.textContent = '('+Object.keys(blocklist.videos).length+')'; - } else { - this.textContent = '(empty)'; - } + this.textContent = '('+Object.keys(blocklist.videos).length+')'; + } else { + this.textContent = '(empty)'; + } } } } diff --git a/menu/skeleton-parts/dark-light-switch.js b/menu/skeleton-parts/dark-light-switch.js index 4affe69ab..0c44d9fb0 100644 --- a/menu/skeleton-parts/dark-light-switch.js +++ b/menu/skeleton-parts/dark-light-switch.js @@ -1,57 +1,57 @@ const isDark = () => { - const themeElement = satus.storage.get('theme') - const lightThemes = ['desert', 'dawn', 'plain', 'default'] - const darkThemes = ['sunset', 'night', 'dark', 'black'] - return darkThemes.includes(themeElement) + const themeElement = satus.storage.get('theme') + const lightThemes = ['desert', 'dawn', 'plain', 'default'] + const darkThemes = ['sunset', 'night', 'dark', 'black'] + return darkThemes.includes(themeElement) } extension.skeleton.header.sectionEnd.darkLightSwitch.svgSun.on = { - render: function () { - console.log(satus.storage.get('lastLightTheme') + " " + satus.storage.get('lastDarkTheme')) - if(isDark()) { - this.style.display = 'none' - } - } + render: function () { + console.log(satus.storage.get('lastLightTheme') + " " + satus.storage.get('lastDarkTheme')) + if(isDark()) { + this.style.display = 'none' + } + } } extension.skeleton.header.sectionEnd.darkLightSwitch.svgMoon.on = { - render: function () { - if(!isDark()) { - this.style.display = 'none' - } - } + render: function () { + if(!isDark()) { + this.style.display = 'none' + } + } } extension.skeleton.header.sectionEnd.darkLightSwitch.on = { - click: function () { - if(isDark()) { - if (satus.storage.get('lastLightTheme')) { - satus.storage.set('theme', satus.storage.get("lastLightTheme")) - } else { - satus.storage.set('theme', 'default') - } - document.getElementById('dark-light-switch-icon-sun').style.display = '' - document.getElementById('dark-light-switch-icon-moon').style.display = 'none' - } else { - if (satus.storage.get('lastDarkTheme')) { - satus.storage.set('theme', satus.storage.get("lastDarkTheme")) - } else { - satus.storage.set('theme', 'black') - } - document.getElementById('dark-light-switch-icon-sun').style.display = 'none' - document.getElementById('dark-light-switch-icon-moon').style.display = '' - } - } + click: function () { + if(isDark()) { + if (satus.storage.get('lastLightTheme')) { + satus.storage.set('theme', satus.storage.get("lastLightTheme")) + } else { + satus.storage.set('theme', 'default') + } + document.getElementById('dark-light-switch-icon-sun').style.display = '' + document.getElementById('dark-light-switch-icon-moon').style.display = 'none' + } else { + if (satus.storage.get('lastDarkTheme')) { + satus.storage.set('theme', satus.storage.get("lastDarkTheme")) + } else { + satus.storage.set('theme', 'black') + } + document.getElementById('dark-light-switch-icon-sun').style.display = 'none' + document.getElementById('dark-light-switch-icon-moon').style.display = '' + } + } } satus.storage.onchanged(() => { - if(isDark()) { - document.getElementById('dark-light-switch-icon-sun').style.display = 'none' - document.getElementById('dark-light-switch-icon-moon').style.display = '' - satus.storage.set('lastDarkTheme', satus.storage.get('theme')) - } else { - document.getElementById('dark-light-switch-icon-sun').style.display = '' - document.getElementById('dark-light-switch-icon-moon').style.display = 'none' - satus.storage.set('lastLightTheme', satus.storage.get('theme')) - } + if(isDark()) { + document.getElementById('dark-light-switch-icon-sun').style.display = 'none' + document.getElementById('dark-light-switch-icon-moon').style.display = '' + satus.storage.set('lastDarkTheme', satus.storage.get('theme')) + } else { + document.getElementById('dark-light-switch-icon-sun').style.display = '' + document.getElementById('dark-light-switch-icon-moon').style.display = 'none' + satus.storage.set('lastLightTheme', satus.storage.get('theme')) + } }) diff --git a/menu/skeleton-parts/general.js b/menu/skeleton-parts/general.js index 2096be572..06e393fb0 100644 --- a/menu/skeleton-parts/general.js +++ b/menu/skeleton-parts/general.js @@ -34,7 +34,7 @@ extension.skeleton.main.layers.section.general = { value: 'below_player' }] }, - /* improvedTubeSidePanel: { + /* improvedTubeSidePanel: { component: 'switch', text: 'improvedTubeSidePanel' }, @@ -42,11 +42,11 @@ extension.skeleton.main.layers.section.general = { component: 'select', text: 'defaultContentCountry', options:[{text:"default",value:"default"},{text:"Afghanistan",value:"AF"},{text:"Albania",value:"AL"},{text:"Algeria",value:"DZ"},{text:"AmericanSamoa",value:"AS"},{text:"Andorra",value:"AD"},{text:"Angola",value:"AO"},{text:"Anguilla",value:"AI"},{text:"Antarctica",value:"AQ"},{text:"AntiguaandBarbuda",value:"AG"},{text:"Argentina",value:"AR"},{text:"Armenia",value:"AM"},{text:"Aruba",value:"AW"},{text:"Australia",value:"AU"},{text:"Austria",value:"AT"},{text:"Azerbaijan",value:"AZ"},{text:"Bahrain",value:"BH"},{text:"BailiwickofGuernsey",value:"GG"},{text:"Bangladesh",value:"BD"},{text:"Barbados",value:"BB"},{text:"Belarus",value:"BY"},{text:"Belgium",value:"BE"},{text:"Belize",value:"BZ"},{text:"Benin",value:"BJ"},{text:"Bermuda",value:"BM"},{text:"Bhutan",value:"BT"},{text:"Bolivia",value:"BO"},{text:"Bonaire",value:"BQ"},{text:"BosniaandHerzegovina",value:"BA"},{text:"Botswana",value:"BW"},{text:"BouvetIsland",value:"BV"},{text:"Brazil",value:"BR"},{text:"BritishIndianOceanTerritory",value:"IO"},{text:"BritishVirginIslands",value:"VG"},{text:"Brunei",value:"BN"},{text:"Bulgaria",value:"BG"},{text:"BurkinaFaso",value:"BF"},{text:"Burundi",value:"BI"},{text:"Cambodia",value:"KH"},{text:"Cameroon",value:"CM"},{text:"Canada",value:"CA"},{text:"CapeVerde",value:"CV"},{text:"CaymanIslands",value:"KY"},{text:"CentralAfricanRepublic",value:"CF"},{text:"Chad",value:"TD"},{text:"Chile",value:"CL"},{text:"China",value:"CN"},{text:"ChristmasIsland",value:"CX"},{text:"Cocos(Keeling)Islands",value:"CC"},{text:"CollectivityofSaintMartin",value:"MF"},{text:"Colombia",value:"CO"},{text:"Comoros",value:"KM"},{text:"CookIslands",value:"CK"},{text:"CostaRica",value:"CR"},{text:"Croatia",value:"HR"},{text:"Cuba",value:"CU"},{text:"Curaçao",value:"CW"},{text:"Cyprus",value:"CY"},{text:"CzechRepublic",value:"CZ"},{text:"DemocraticRepublicoftheCongo",value:"CD"},{text:"Denmark",value:"DK"},{text:"Djibouti",value:"DJ"},{text:"Dominica",value:"DM"},{text:"DominicanRepublic",value:"DO"},{text:"EastTimor",value:"TL"},{text:"Ecuador",value:"EC"},{text:"Egypt",value:"EG"},{text:"ElSalvador",value:"SV"},{text:"EquatorialGuinea",value:"GQ"},{text:"Eritrea",value:"ER"},{text:"Estonia",value:"EE"},{text:"Eswatini",value:"SZ"},{text:"Ethiopia",value:"ET"},{text:"FalklandIslands",value:"FK"},{text:"FaroeIslands",value:"FO"},{text:"FederatedStatesofMicronesia",value:"FM"},{text:"Fiji",value:"FJ"},{text:"Finland",value:"FI"},{text:"France",value:"FR"},{text:"FrenchGuiana",value:"GF"},{text:"FrenchPolynesia",value:"PF"},{text:"FrenchSouthernandAntarcticLands",value:"TF"},{text:"Gabon",value:"GA"},{text:"Georgia(country)",value:"GE"},{text:"Germany",value:"DE"},{text:"Ghana",value:"GH"},{text:"Gibraltar",value:"GI"},{text:"Greece",value:"GR"},{text:"Greenland",value:"GL"},{text:"Grenada",value:"GD"},{text:"Guadeloupe",value:"GP"},{text:"Guam",value:"GU"},{text:"Guatemala",value:"GT"},{text:"Guinea",value:"GN"},{text:"Guinea-Bissau",value:"GW"},{text:"Guyana",value:"GY"},{text:"Haiti",value:"HT"},{text:"HeardIslandandMcDonaldIslands",value:"HM"},{text:"HolySee",value:"VA"},{text:"Honduras",value:"HN"},{text:"HongKong",value:"HK"},{text:"Hungary",value:"HU"},{text:"Iceland",value:"IS"},{text:"India",value:"IN"},{text:"Indonesia",value:"ID"},{text:"Iran",value:"IR"},{text:"Iraq",value:"IQ"},{text:"IsleofMan",value:"IM"},{text:"Israel",value:"IL"},{text:"Italy",value:"IT"},{text:"IvoryCoast",value:"CI"},{text:"Jamaica",value:"JM"},{text:"Japan",value:"JP"},{text:"Jersey",value:"JE"},{text:"Jordan",value:"JO"},{text:"Kazakhstan",value:"KZ"},{text:"Kenya",value:"KE"},{text:"Kiribati",value:"KI"},{text:"Kuwait",value:"KW"},{text:"Kyrgyzstan",value:"KG"},{text:"Laos",value:"LA"},{text:"Latvia",value:"LV"},{text:"Lebanon",value:"LB"},{text:"Lesotho",value:"LS"},{text:"Liberia",value:"LR"},{text:"Libya",value:"LY"},{text:"Liechtenstein",value:"LI"},{text:"Lithuania",value:"LT"},{text:"Luxembourg",value:"LU"},{text:"Macau",value:"MO"},{text:"Madagascar",value:"MG"},{text:"Malawi",value:"MW"},{text:"Malaysia",value:"MY"},{text:"Maldives",value:"MV"},{text:"Mali",value:"ML"},{text:"Malta",value:"MT"},{text:"MarshallIslands",value:"MH"},{text:"Martinique",value:"MQ"},{text:"Mauritania",value:"MR"},{text:"Mauritius",value:"MU"},{text:"Mayotte",value:"YT"},{text:"Mexico",value:"MX"},{text:"Moldova",value:"MD"},{text:"Monaco",value:"MC"},{text:"Mongolia",value:"MN"},{text:"Montenegro",value:"ME"},{text:"Montserrat",value:"MS"},{text:"Morocco",value:"MA"},{text:"Mozambique",value:"MZ"},{text:"Myanmar",value:"MM"},{text:"Namibia",value:"NA"},{text:"Nauru",value:"NR"},{text:"Nepal",value:"NP"},{text:"Netherlands",value:"NL"},{text:"NewCaledonia",value:"NC"},{text:"NewZealand",value:"NZ"},{text:"Nicaragua",value:"NI"},{text:"Niger",value:"NE"},{text:"Nigeria",value:"NG"},{text:"Niue",value:"NU"},{text:"NorfolkIsland",value:"NF"},{text:"NorthKorea",value:"KP"},{text:"NorthMacedonia",value:"MK"},{text:"NorthernMarianaIslands",value:"MP"},{text:"Norway",value:"NO"},{text:"Oman",value:"OM"},{text:"Pakistan",value:"PK"},{text:"Palau",value:"PW"},{text:"Panama",value:"PA"},{text:"PapuaNewGuinea",value:"PG"},{text:"Paraguay",value:"PY"},{text:"Peru",value:"PE"},{text:"Philippines",value:"PH"},{text:"PitcairnIslands",value:"PN"},{text:"Poland",value:"PL"},{text:"Portugal",value:"PT"},{text:"PuertoRico",value:"PR"},{text:"Qatar",value:"QA"},{text:"RepublicofIreland",value:"IE"},{text:"RepublicoftheCongo",value:"CG"},{text:"Romania",value:"RO"},{text:"Russia",value:"RU"},{text:"Rwanda",value:"RW"},{text:"Réunion",value:"RE"},{text:"SaintBarthélemy",value:"BL"},{text:"SaintHelena",value:"SH"},{text:"SaintKittsandNevis",value:"KN"},{text:"SaintLucia",value:"LC"},{text:"SaintPierreandMiquelon",value:"PM"},{text:"SaintVincentandtheGrenadines",value:"VC"},{text:"Samoa",value:"WS"},{text:"SanMarino",value:"SM"},{text:"SaudiArabia",value:"SA"},{text:"Senegal",value:"SN"},{text:"Serbia",value:"RS"},{text:"Seychelles",value:"SC"},{text:"SierraLeone",value:"SL"},{text:"Singapore",value:"SG"},{text:"SintMaarten",value:"SX"},{text:"Slovakia",value:"SK"},{text:"Slovenia",value:"SI"},{text:"SolomonIslands",value:"SB"},{text:"Somalia",value:"SO"},{text:"SouthAfrica",value:"ZA"},{text:"SouthGeorgiaandtheSouthSandwichIslands",value:"GS"},{text:"SouthKorea",value:"KR"},{text:"SouthSudan",value:"SS"},{text:"Spain",value:"ES"},{text:"SriLanka",value:"LK"},{text:"StateofPalestine",value:"PS"},{text:"Sudan",value:"SD"},{text:"Suriname",value:"SR"},{text:"Svalbard",value:"SJ"},{text:"Sweden",value:"SE"},{text:"Switzerland",value:"CH"},{text:"Syria",value:"SY"},{text:"SãoToméandPríncipe",value:"ST"},{text:"Taiwan",value:"TW"},{text:"Tajikistan",value:"TJ"},{text:"Tanzania",value:"TZ"},{text:"Thailand",value:"TH"},{text:"TheBahamas",value:"BS"},{text:"TheGambia",value:"GM"},{text:"Togo",value:"TG"},{text:"Tokelau",value:"TK"},{text:"Tonga",value:"TO"},{text:"TrinidadandTobago",value:"TT"},{text:"Tunisia",value:"TN"},{text:"Turkey",value:"TR"},{text:"Turkmenistan",value:"TM"},{text:"TurksandCaicosIslands",value:"TC"},{text:"Tuvalu",value:"TV"},{text:"Uganda",value:"UG"},{text:"Ukraine",value:"UA"},{text:"UnitedArabEmirates",value:"AE"},{text:"UnitedKingdom",value:"GB"},{text:"UnitedStatesVirginIslands",value:"VI"},{text:"UnitedStates",value:"UM"},{text:"UnitedStates",value:"US"},{text:"Uruguay",value:"UY"},{text:"Uzbekistan",value:"UZ"},{text:"Vanuatu",value:"VU"},{text:"Venezuela",value:"VE"},{text:"Vietnam",value:"VN"},{text:"WallisandFutuna",value:"WF"},{text:"WesternSahara",value:"EH"},{text:"Yemen",value:"YE"},{text:"Zambia",value:"ZM"},{text:"Zimbabwe",value:"ZW"},{text:"ÅlandIslands",value:"AX"}] - }, + }, cursorLighting: { component: 'switch', text: 'cursorLighting', - }, + }, ads: { text: 'ads', component: 'select', @@ -88,20 +88,20 @@ extension.skeleton.main.layers.section.general = { class: "count-component", }, search: { - component: 'section', - variant: 'card', - title: 'Youtube_Search', - remove_related_search_results: { - component: 'switch', - text: 'removeRelatedSearchResults' - }, - open_new_tab: { - component: "switch", - text: "openNewTab", - }, - remove_shorts_reel_search_results: { - component: 'switch', - text: 'removeShortsReelSearchResults' + component: 'section', + variant: 'card', + title: 'Youtube_Search', + remove_related_search_results: { + component: 'switch', + text: 'removeRelatedSearchResults' + }, + open_new_tab: { + component: "switch", + text: "openNewTab", + }, + remove_shorts_reel_search_results: { + component: 'switch', + text: 'removeShortsReelSearchResults' } }, remove_home_page_shorts: { @@ -183,7 +183,7 @@ extension.skeleton.main.layers.section.general = { text: 'hideAnimatedThumbnails', tags: 'preview' }, - disable_thumbnail_playback: { + disable_thumbnail_playback: { component: 'switch', text: 'disableThumbnailPlayback', }, diff --git a/menu/skeleton-parts/player.js b/menu/skeleton-parts/player.js index 7236b0b00..4dd215948 100644 --- a/menu/skeleton-parts/player.js +++ b/menu/skeleton-parts/player.js @@ -572,7 +572,7 @@ extension.skeleton.main.layers.section.player.on.click = { component: 'select', text: 'fontSize', options: [{ - text: '100%', + text: '100%', value: 0 }, { text: '75%', @@ -757,11 +757,11 @@ extension.skeleton.main.layers.section.player.on.click = { }, on: { render: function () { - extension.skeleton.main.layers.section.player.on.click.section_1.player_quality.on.render.call(this); + extension.skeleton.main.layers.section.player.on.click.section_1.player_quality.on.render.call(this); } } }, - /* +/* qualityWhenRunningOnBattery: { component: 'select', text: 'qualityWhenRunningOnBattery', diff --git a/menu/skeleton-parts/themes.js b/menu/skeleton-parts/themes.js index 506a31c50..01436c4ae 100644 --- a/menu/skeleton-parts/themes.js +++ b/menu/skeleton-parts/themes.js @@ -51,10 +51,10 @@ extension.skeleton.main.layers.section.themes.on.click.section = { variant: satus.storage.get('theme') == 'dark' ? 'dark-theme' : 'default-theme', text: satus.storage.get('theme') == 'dark' ? 'youtubesDark' : 'youtubesLight', radio: { - component: 'radio', - group: 'theme', - value: satus.storage.get('theme') == 'dark' ? 'dark' : 'light', - ...(!satus.storage.get('theme') && { checked: true }) + component: 'radio', + group: 'theme', + value: satus.storage.get('theme') == 'dark' ? 'dark' : 'light', + ...(!satus.storage.get('theme') && { checked: true }) } } }, @@ -64,10 +64,10 @@ extension.skeleton.main.layers.section.themes.on.click.section = { variant: satus.storage.get('theme') == 'dark' ? 'default-theme' : 'dark-theme', text: satus.storage.get('theme') == 'dark' ? 'youtubesLight' : 'youtubesDark', radio: { - component: 'radio', - group: 'theme', - value: satus.storage.get('theme') == 'dark' ? 'light' : 'dark', - ...(satus.storage.get('theme') == 'dark' && { checked: true }) + component: 'radio', + group: 'theme', + value: satus.storage.get('theme') == 'dark' ? 'light' : 'dark', + ...(satus.storage.get('theme') == 'dark' && { checked: true }) } } }, diff --git a/unit/core.test.js b/unit/core.test.js index 21195bde4..57b6ee067 100644 --- a/unit/core.test.js +++ b/unit/core.test.js @@ -38,21 +38,21 @@ jest.mock('../../js&css/extension/core', () => ({ trigger: async function (type, data) { const listeners = this.listeners[type]; - if (listeners) { - for (let i = 0, l = listeners.length; i < l; i++) { - const listener = listeners[i]; - - if (typeof listener === 'function') { - if (listener instanceof (async function () { }).constructor === true) { - await listener(data); - } else { - listener(data); - } - } - } - } - }, - }, + if (listeners) { + for (let i = 0, l = listeners.length; i < l; i++) { + const listener = listeners[i]; + + if (typeof listener === 'function') { + if (listener instanceof (async function () { }).constructor === true) { + await listener(data); + } else { + listener(data); + } + } + } + } + }, + }, })); @@ -62,58 +62,58 @@ const extensionMock = require('../js&css/extension/core'); // Unit tests for the camelize function test('Convert snake_case to camelCase', () => { - const input = 'snake_case_example'; - const expectedOutput = 'snakeCaseExample'; + const input = 'snake_case_example'; + const expectedOutput = 'snakeCaseExample'; - const mockInput = extensionMock.camelize(input); + const mockInput = extensionMock.camelize(input); - expect(mockInput).toBe(expectedOutput); + expect(mockInput).toBe(expectedOutput); }); test('Convert kebab-case to camelCase', () => { - // Define input and expected output - const input = 'kebab-case-example'; - const expectedOutput = 'kebabCaseExample'; + // Define input and expected output + const input = 'kebab-case-example'; + const expectedOutput = 'kebabCaseExample'; - // Call the camelize function with the input - const mockInput = extensionMock.camelize(input); + // Call the camelize function with the input + const mockInput = extensionMock.camelize(input); - // Check if the result matches the expected output - expect(mockInput).toBe(expectedOutput); + // Check if the result matches the expected output + expect(mockInput).toBe(expectedOutput); }); // Unit test for the events method test('Trigger method should correctly retrieve and invoke listeners', () => { - // Mock event listeners - const listener1 = jest.fn(); - const listener2 = jest.fn(); - const listener3 = jest.fn(); + // Mock event listeners + const listener1 = jest.fn(); + const listener2 = jest.fn(); + const listener3 = jest.fn(); - // Register listeners for a specific event type - extensionMock.events.listeners['eventType'] = [listener1, listener2, listener3]; + // Register listeners for a specific event type + extensionMock.events.listeners['eventType'] = [listener1, listener2, listener3]; - // Call the trigger method with the event type and data - extensionMock.events.trigger('eventType', { data: 'example' }); + // Call the trigger method with the event type and data + extensionMock.events.trigger('eventType', { data: 'example' }); - // Verify that each listener is invoked with the provided data - expect(listener1).toHaveBeenCalledWith({ data: 'example' }); - expect(listener2).toHaveBeenCalledWith({ data: 'example' }); - expect(listener3).toHaveBeenCalledWith({ data: 'example' }); + // Verify that each listener is invoked with the provided data + expect(listener1).toHaveBeenCalledWith({ data: 'example' }); + expect(listener2).toHaveBeenCalledWith({ data: 'example' }); + expect(listener3).toHaveBeenCalledWith({ data: 'example' }); }); test('Trigger method should handle asynchronous listeners', async () => { - // Mock asynchronous event listeners - const asyncListener = jest.fn().mockImplementation(async () => { - // Simulate asynchronous behavior - await new Promise(resolve => setTimeout(resolve, 100)); - }); + // Mock asynchronous event listeners + const asyncListener = jest.fn().mockImplementation(async () => { + // Simulate asynchronous behavior + await new Promise(resolve => setTimeout(resolve, 100)); + }); - // Register the asynchronous listener for a specific event type - extensionMock.events.listeners['eventType'] = [asyncListener]; + // Register the asynchronous listener for a specific event type + extensionMock.events.listeners['eventType'] = [asyncListener]; - // Call the trigger method with the event type and data - await extensionMock.events.trigger('eventType', { data: 'example' }); + // Call the trigger method with the event type and data + await extensionMock.events.trigger('eventType', { data: 'example' }); - // Verify that the asynchronous listener is invoked with the provided data - expect(asyncListener).toHaveBeenCalledWith({ data: 'example' }); + // Verify that the asynchronous listener is invoked with the provided data + expect(asyncListener).toHaveBeenCalledWith({ data: 'example' }); }); From 601a403505d8ae3c75b73527a7a3c114f98930c1 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 20:44:58 +0800 Subject: [PATCH 05/17] Fixed code indent --- background.js | 4 +- eslint.config.mjs | 6 +- jest.config.js | 12 +- js&css/extension/core.js | 2 +- js&css/extension/init.js | 4 +- .../www.youtube.com/general/general.js | 310 +++---- js&css/web-accessible/core.js | 6 +- js&css/web-accessible/functions.js | 112 +-- js&css/web-accessible/init.js | 4 +- .../www.youtube.com/appearance.js | 816 +++++++++--------- .../www.youtube.com/blocklist.js | 28 +- .../web-accessible/www.youtube.com/channel.js | 48 +- .../web-accessible/www.youtube.com/player.js | 476 +++++----- .../www.youtube.com/playlist.js | 98 +-- .../www.youtube.com/shortcuts.js | 46 +- .../web-accessible/www.youtube.com/themes.js | 50 +- menu/index.js | 4 +- menu/satus.js | 34 +- menu/skeleton-parts/appearance.js | 518 +++++------ menu/skeleton-parts/blocklist.js | 16 +- menu/skeleton-parts/dark-light-switch.js | 88 +- menu/skeleton-parts/general.js | 40 +- menu/skeleton-parts/player.js | 12 +- menu/skeleton-parts/search.js | 4 +- menu/skeleton-parts/themes.js | 16 +- menu/skeleton.js | 2 +- unit/core.test.js | 98 +-- 27 files changed, 1429 insertions(+), 1425 deletions(-) diff --git a/background.js b/background.js index 311e4040a..441a17ff3 100644 --- a/background.js +++ b/background.js @@ -206,13 +206,13 @@ function tabPrune(callback) { }; /*-------------------------------------------------------------- # TAB FOCUS/BLUR - commented out console.log left intentionally, to help understand + commented out console.log left intentionally, to help understand https://issues.chromium.org/issues/41116352 --------------------------------------------------------------*/ let tab = {}, tabPrev = {}, windowId; - + chrome.tabs.onActivated.addListener(function (activeInfo) { tabPrev = tab; tab = activeInfo; diff --git a/eslint.config.mjs b/eslint.config.mjs index aef539513..db5da1eb4 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -30,10 +30,14 @@ export default [...compat.extends("eslint:recommended"), { } }, rules: { - indent: ["error", "tab"], + indent: ["error", "tab", {"SwitchCase": 1}], "no-empty": ["error", { "allowEmptyCatch": true }], "no-unused-vars": ["error", { "caughtErrors": "none" }], "no-undef": ["off"], + "no-trailing-spaces": "warn", + "no-multi-spaces": "warn", + "no-fallthrough": ["error", { "allowEmptyCase": true }], + "no-implicit-globals": "error", "max-len": ["error", { code: 255, ignoreUrls: true, diff --git a/jest.config.js b/jest.config.js index 0ad591433..5e9923b5e 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,8 +1,8 @@ module.exports = { - testPathIgnorePatterns: [ - "/node_modules/" - ], - testMatch: [ - "**/tests/**/*.js" - ] + testPathIgnorePatterns: [ + "/node_modules/" + ], + testMatch: [ + "**/tests/**/*.js" + ] }; diff --git a/js&css/extension/core.js b/js&css/extension/core.js index 6d0e44987..f368ae817 100644 --- a/js&css/extension/core.js +++ b/js&css/extension/core.js @@ -117,7 +117,7 @@ extension.events.trigger = async function (type, data) { /*-------------------------------------------------------------- # INJECT ---------------------------------------------------------------- - + --------------------------------------------------------------*/ extension.inject = function (paths, callback) { diff --git a/js&css/extension/init.js b/js&css/extension/init.js index b6f5e5116..78e7308e8 100644 --- a/js&css/extension/init.js +++ b/js&css/extension/init.js @@ -243,6 +243,6 @@ document.addEventListener('it-message-from-youtube', function () { document.addEventListener('it-play', function (event) { var videos = document.querySelectorAll('video'); - try {chrome.runtime.sendMessage({action: 'play'})} - catch(error){console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } + try {chrome.runtime.sendMessage({action: 'play'})} + catch(error){console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } }); diff --git a/js&css/extension/www.youtube.com/general/general.js b/js&css/extension/www.youtube.com/general/general.js index a6a06d4b6..9ce6ef88c 100644 --- a/js&css/extension/www.youtube.com/general/general.js +++ b/js&css/extension/www.youtube.com/general/general.js @@ -154,36 +154,36 @@ extension.features.onlyOnePlayerInstancePlaying = function () { # ADD "SCROLL TO TOP" --------------------------------------------------------------*/ extension.features.addScrollToTop = function (event) { - if (event instanceof Event) { - if (window.scrollY > window.innerHeight / 2) { - document.documentElement.setAttribute('it-scroll-to-top', 'true'); - } else { - document.documentElement.removeAttribute('it-scroll-to-top'); - } - } else { - if (extension.storage.get('add_scroll_to_top') === true) { - this.addScrollToTop.button = document.createElement('div'); - this.addScrollToTop.button.id = 'it-scroll-to-top'; - this.addScrollToTop.button.className = 'satus-div'; - var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - svg.setAttribute('viewBox', '0 0 24 24'); - var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttribute('d', 'M13 19V7.8l4.9 5c.4.3 1 .3 1.4 0 .4-.5.4-1.1 0-1.5l-6.6-6.6a1 1 0 0 0-1.4 0l-6.6 6.6a1 1 0 1 0 1.4 1.4L11 7.8V19c0 .6.5 1 1 1s1-.5 1-1z'); - svg.appendChild(path); - this.addScrollToTop.button.appendChild(svg); - window.addEventListener('scroll', function () { document.body.appendChild(extension.features.addScrollToTop.button); }); - this.addScrollToTop.button.addEventListener('click', function () { - window.scrollTo(0, 0); - document.getElementById('it-scroll-to-top')?.remove(); - }); - } - if (extension.storage.get('add_scroll_to_top') === true) { - window.addEventListener('scroll', extension.features.addScrollToTop); - } else if (this.addScrollToTop.button) { - window.removeEventListener('scroll', extension.features.addScrollToTop); - this.addScrollToTop.button.remove(); - } - } + if (event instanceof Event) { + if (window.scrollY > window.innerHeight / 2) { + document.documentElement.setAttribute('it-scroll-to-top', 'true'); + } else { + document.documentElement.removeAttribute('it-scroll-to-top'); + } + } else { + if (extension.storage.get('add_scroll_to_top') === true) { + this.addScrollToTop.button = document.createElement('div'); + this.addScrollToTop.button.id = 'it-scroll-to-top'; + this.addScrollToTop.button.className = 'satus-div'; + var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('d', 'M13 19V7.8l4.9 5c.4.3 1 .3 1.4 0 .4-.5.4-1.1 0-1.5l-6.6-6.6a1 1 0 0 0-1.4 0l-6.6 6.6a1 1 0 1 0 1.4 1.4L11 7.8V19c0 .6.5 1 1 1s1-.5 1-1z'); + svg.appendChild(path); + this.addScrollToTop.button.appendChild(svg); + window.addEventListener('scroll', function () { document.body.appendChild(extension.features.addScrollToTop.button); }); + this.addScrollToTop.button.addEventListener('click', function () { + window.scrollTo(0, 0); + document.getElementById('it-scroll-to-top')?.remove(); + }); + } + if (extension.storage.get('add_scroll_to_top') === true) { + window.addEventListener('scroll', extension.features.addScrollToTop); + } else if (this.addScrollToTop.button) { + window.removeEventListener('scroll', extension.features.addScrollToTop); + this.addScrollToTop.button.remove(); + } + } }; /*-------------------------------------------------------------- # CONFIRMATION BEFORE CLOSING @@ -235,43 +235,43 @@ extension.features.popupWindowButtons = function (event) { while (detected === false && target.parentNode) { if ( target.className && typeof target.className === 'string' && (( target.id === 'thumbnail' && target.className.indexOf('ytd-thumbnail') !== -1 || target.className.indexOf('thumb-link') !== -1 ) - || (target.className.indexOf('video-preview') !== -1 || target.className.indexOf('ytp-inline-preview-scrim') !== -1 || target.className.indexOf('ytp-inline-preview-ui') !== -1) + || (target.className.indexOf('video-preview') !== -1 || target.className.indexOf('ytp-inline-preview-scrim') !== -1 || target.className.indexOf('ytp-inline-preview-ui') !== -1) )) { if (!target.itPopupWindowButton) { -target.itPopupWindowButton = document.createElement('button'); -target.itPopupWindowButton.className = 'it-popup-window'; - -var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); -svg.setAttribute('viewBox', '0 0 24 24'); -var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); -path.setAttribute('d', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z'); -svg.appendChild(path); -target.itPopupWindowButton.appendChild(svg); -target.appendChild(target.itPopupWindowButton); - -target.itPopupWindowButton.addEventListener('click', function (event) { - event.preventDefault(); - event.stopPropagation(); - try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch(error) { console.log(error)}; - ytPlayer = document.querySelector("#movie_player"); - if (ytPlayer){width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} - else { width = innerWidth * 0.4; height = innerHeight * 0.4; } - if (!ytPlayer) { - let shorts = /short/.test(this.parentElement.href); - if ( width / height < 1 ) { let vertical = true } else { let vertical = false } - if ( !vertical && shorts ){ width = height * 0.6} - if ( vertical && !shorts ){ height = width * 0.6} - } - - window.open('https://www.youtube.com/embed/' + this.dataset.id + '?autoplay=' + (extension.storage.get('player_autoplay_disable') ? '0' : '1'), '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); - chrome.runtime.sendMessage({ - action: 'fixPopup', - width: width, - height: height, - title: this.parentElement.closest('*[id="video-title"]')?.textContent + " - Youtube" - }) - }); - } + target.itPopupWindowButton = document.createElement('button'); + target.itPopupWindowButton.className = 'it-popup-window'; + + var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('d', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z'); + svg.appendChild(path); + target.itPopupWindowButton.appendChild(svg); + target.appendChild(target.itPopupWindowButton); + + target.itPopupWindowButton.addEventListener('click', function (event) { + event.preventDefault(); + event.stopPropagation(); + try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch(error) { console.log(error)}; + ytPlayer = document.querySelector("#movie_player"); + if (ytPlayer){width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} + else { width = innerWidth * 0.4; height = innerHeight * 0.4; } + if (!ytPlayer) { + let shorts = /short/.test(this.parentElement.href); + if ( width / height < 1 ) { let vertical = true } else { let vertical = false } + if ( !vertical && shorts ){ width = height * 0.6} + if ( vertical && !shorts ){ height = width * 0.6} + } + + window.open('https://www.youtube.com/embed/' + this.dataset.id + '?autoplay=' + (extension.storage.get('player_autoplay_disable') ? '0' : '1'), '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); + chrome.runtime.sendMessage({ + action: 'fixPopup', + width: width, + height: height, + title: this.parentElement.closest('*[id="video-title"]')?.textContent + " - Youtube" + }) + }); + } detected = true; } target = target.parentNode; @@ -344,46 +344,46 @@ extension.features.markWatchedVideos = function (anything) { ) ) { if (!target.itMarkWatchedVideosButton) { - target.itMarkWatchedVideosButton = document.createElement('button'); - target.itMarkWatchedVideosButton.className = 'it-mark-watched-videos'; - target.itMarkWatchedVideosButton.dataset.id = extension.functions.getUrlParameter(target.href, 'v'); - var id = target.itMarkWatchedVideosButton.dataset.id; - var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); - var pathData = 'M12 15.15q1.525 0 2.588-1.063 1.062-1.062 1.062-2.587 0-1.525-1.062-2.588Q13.525 7.85 12 7.85q-1.525 0-2.587 1.062Q8.35 9.975 8.35 11.5q0 1.525 1.063 2.587Q10.475 15.15 12 15.15Zm0-.95q-1.125 0-1.912-.788Q9.3 12.625 9.3 11.5t.788-1.913Q10.875 8.8 12 8.8t1.913.787q.787.788.787 1.913t-.787 1.912q-.788.788-1.913.788Zm0 3.8q-3.1 0-5.688-1.613Q3.725 14.775 2.325 12q-.05-.1-.075-.225-.025-.125-.025-.275 0-.15.025-.275.025-.125.075-.225 1.4-2.775 3.987-4.388Q8.9 5 12 5q3.1 0 5.688 1.612Q20.275 8.225 21.675 11q.05.1.075.225.025.125.025.275 0 .15-.025.275-.025.125-.075.225-1.4 2.775-3.987 4.387Q15.1 18 12 18Z'; - var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttribute('d', pathData + 'm0-6.5Zm0 5.5q2.825 0 5.188-1.488Q19.55 14.025 20.8 11.5q-1.25-2.525-3.612-4.013Q14.825 6 12 6 9.175 6 6.812 7.487 4.45 8.975 3.2 11.5q1.25 2.525 3.612 4.012Q9.175 17 12 17Z'); - svg.appendChild(path); - var svg2 = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg2.setAttribute('viewBox', '0 0 24 24'); - var extraPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - extraPath.setAttribute('d', pathData); - svg2.appendChild(extraPath); - target.itMarkWatchedVideosButton.appendChild(svg); - target.itMarkWatchedVideosButton.appendChild(svg2); - if (extension.storage.get('watched') && extension.storage.get('watched')[id]) { - target.itMarkWatchedVideosButton.setAttribute('watched', '')}; - target.appendChild(target.itMarkWatchedVideosButton); - target.itMarkWatchedVideosButton.addEventListener('click', function (event) { - var id = this.dataset.id, - value = this.toggleAttribute('watched'); - - event.preventDefault(); - event.stopPropagation(); - - if (!extension.storage.watched) { - extension.storage.watched = {}; - } - - if (value) { - extension.storage.get('watched')[id] = { - title: '' - }; - } else { - delete extension.storage.get('watched')[id]; - } - - chrome.storage.local.set({ - watched: extension.storage.get('watched') - });}); + target.itMarkWatchedVideosButton = document.createElement('button'); + target.itMarkWatchedVideosButton.className = 'it-mark-watched-videos'; + target.itMarkWatchedVideosButton.dataset.id = extension.functions.getUrlParameter(target.href, 'v'); + var id = target.itMarkWatchedVideosButton.dataset.id; + var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); + var pathData = 'M12 15.15q1.525 0 2.588-1.063 1.062-1.062 1.062-2.587 0-1.525-1.062-2.588Q13.525 7.85 12 7.85q-1.525 0-2.587 1.062Q8.35 9.975 8.35 11.5q0 1.525 1.063 2.587Q10.475 15.15 12 15.15Zm0-.95q-1.125 0-1.912-.788Q9.3 12.625 9.3 11.5t.788-1.913Q10.875 8.8 12 8.8t1.913.787q.787.788.787 1.913t-.787 1.912q-.788.788-1.913.788Zm0 3.8q-3.1 0-5.688-1.613Q3.725 14.775 2.325 12q-.05-.1-.075-.225-.025-.125-.025-.275 0-.15.025-.275.025-.125.075-.225 1.4-2.775 3.987-4.388Q8.9 5 12 5q3.1 0 5.688 1.612Q20.275 8.225 21.675 11q.05.1.075.225.025.125.025.275 0 .15-.025.275-.025.125-.075.225-1.4 2.775-3.987 4.387Q15.1 18 12 18Z'; + var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('d', pathData + 'm0-6.5Zm0 5.5q2.825 0 5.188-1.488Q19.55 14.025 20.8 11.5q-1.25-2.525-3.612-4.013Q14.825 6 12 6 9.175 6 6.812 7.487 4.45 8.975 3.2 11.5q1.25 2.525 3.612 4.012Q9.175 17 12 17Z'); + svg.appendChild(path); + var svg2 = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg2.setAttribute('viewBox', '0 0 24 24'); + var extraPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + extraPath.setAttribute('d', pathData); + svg2.appendChild(extraPath); + target.itMarkWatchedVideosButton.appendChild(svg); + target.itMarkWatchedVideosButton.appendChild(svg2); + if (extension.storage.get('watched') && extension.storage.get('watched')[id]) { + target.itMarkWatchedVideosButton.setAttribute('watched', '')}; + target.appendChild(target.itMarkWatchedVideosButton); + target.itMarkWatchedVideosButton.addEventListener('click', function (event) { + var id = this.dataset.id, + value = this.toggleAttribute('watched'); + + event.preventDefault(); + event.stopPropagation(); + + if (!extension.storage.watched) { + extension.storage.watched = {}; + } + + if (value) { + extension.storage.get('watched')[id] = { + title: '' + }; + } else { + delete extension.storage.get('watched')[id]; + } + + chrome.storage.local.set({ + watched: extension.storage.get('watched') + });}); } else { var button = target.itMarkWatchedVideosButton; @@ -516,18 +516,18 @@ extension.features.thumbnailsQuality = function (anything) { # DISABLE VIDEO PLAYBACK ON HOVER --------------------------------------------------------------*/ extension.features.disableThumbnailPlayback = function (event) { - if (event instanceof Event) { - if (event.composedPath().some(elem => (elem.matches != null && elem.matches('#content.ytd-rich-item-renderer, #contents.ytd-item-section-renderer')) - )) { - event.stopImmediatePropagation(); - } - } else { - if (extension.storage.get('disable_thumbnail_playback') === true) { - window.addEventListener('mouseenter', this.disableThumbnailPlayback, true); - } else { - window.removeEventListener('mouseenter', this.disableThumbnailPlayback, true); - } - } + if (event instanceof Event) { + if (event.composedPath().some(elem => (elem.matches != null && elem.matches('#content.ytd-rich-item-renderer, #contents.ytd-item-section-renderer')) + )) { + event.stopImmediatePropagation(); + } + } else { + if (extension.storage.get('disable_thumbnail_playback') === true) { + window.addEventListener('mouseenter', this.disableThumbnailPlayback, true); + } else { + window.removeEventListener('mouseenter', this.disableThumbnailPlayback, true); + } + } }; /*-------------------------------------------------------------- @@ -536,50 +536,50 @@ extension.features.disableThumbnailPlayback = function (event) { extension.features.openNewTab = function (){ if (extension.storage.get("open_new_tab") === true) { - window.onload = function () { - const searchButton = document.querySelector("button#search-icon-legacy"); - const inputField = document.querySelector("input#search"); + window.onload = function () { + const searchButton = document.querySelector("button#search-icon-legacy"); + const inputField = document.querySelector("input#search"); - searchButton.addEventListener("mousedown", (event) => { + searchButton.addEventListener("mousedown", (event) => { performSearchNewTab(inputField.value); }); - inputField.addEventListener("keydown", function (event) { - if (event.key === "Enter") { - performSearchNewTab(inputField.value); - } - }); + inputField.addEventListener("keydown", function (event) { + if (event.key === "Enter") { + performSearchNewTab(inputField.value); + } + }); - let searchedAlready = false; - inputField.addEventListener("focus", function () { - searchedAlready = false; - const observer = new MutationObserver(applySuggestionListeners); - const container = document.querySelector("div[style*='position: fixed'] ul[role='listbox']"); - if (container) observer.observe(container, { attributes: true, childList: true, subtree: true }); -}); - - inputField.addEventListener("input", () => searchedAlready = false); - - function applySuggestionListeners() { - const suggestionContainers = document.querySelectorAll("div[class^='sbqs'], div[class^='sbpqs']"); - suggestionContainers.forEach((suggestionsContainer) => { - suggestionsContainer.addEventListener("mousedown", (event) => { - const suggestionListItem = event.target.closest("li[role='presentation']"); - if (suggestionListItem && !searchedAlready) { - const query = suggestionListItem.querySelector("b").textContent - performSearchNewTab(inputField.value + query); - searchedAlready = true; - } - }); - }); -} + let searchedAlready = false; + inputField.addEventListener("focus", function () { + searchedAlready = false; + const observer = new MutationObserver(applySuggestionListeners); + const container = document.querySelector("div[style*='position: fixed'] ul[role='listbox']"); + if (container) observer.observe(container, { attributes: true, childList: true, subtree: true }); + }); - function performSearchNewTab(query) { - inputField.value = ""; - inputField.focus(); - const newTabURL = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`; - window.open(newTabURL, '_blank'); + inputField.addEventListener("input", () => searchedAlready = false); + + function applySuggestionListeners() { + const suggestionContainers = document.querySelectorAll("div[class^='sbqs'], div[class^='sbpqs']"); + suggestionContainers.forEach((suggestionsContainer) => { + suggestionsContainer.addEventListener("mousedown", (event) => { + const suggestionListItem = event.target.closest("li[role='presentation']"); + if (suggestionListItem && !searchedAlready) { + const query = suggestionListItem.querySelector("b").textContent + performSearchNewTab(inputField.value + query); + searchedAlready = true; + } + }); + }); + } + + function performSearchNewTab(query) { + inputField.value = ""; + inputField.focus(); + const newTabURL = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`; + window.open(newTabURL, '_blank'); + } } } - } } diff --git a/js&css/web-accessible/core.js b/js&css/web-accessible/core.js index 6075d832a..ea4aa724e 100644 --- a/js&css/web-accessible/core.js +++ b/js&css/web-accessible/core.js @@ -181,7 +181,7 @@ document.addEventListener('it-message-from-extension', function () { if (ImprovedTube.storage.block_vp9 || ImprovedTube.storage.block_av1 || ImprovedTube.storage.block_h264) { let atlas = {block_vp9:'vp9|vp09', block_h264:'avc1', block_av1:'av01'}, codec = Object.keys(atlas).reduce(function (all, key) { - return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all}, ''); + return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all}, ''); if (localStorage['it-codec'] != codec) { localStorage['it-codec'] = codec; } @@ -390,12 +390,12 @@ document.addEventListener('it-message-from-extension', function () { case 'subtitlesBackgroundOpacity': ImprovedTube.subtitlesUserSettings(); break - + case 'playerHideControls': ImprovedTube.playerControls(); break case 'playerlistUpNextAutoplay': - if (this.storage.playlist_up_next_autoplay !== false) { + if (this.storage.playlist_up_next_autoplay !== false) { if (playlistData.currentIndex != playlistData.localCurrentIndex) { playlistData.currentIndex = playlistData.localCurrentIndex;} } break } diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index b504d9aab..88c3a85ef 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -14,14 +14,14 @@ ImprovedTube.childHandler = function (node) { ImprovedTube.childHandler(children[i]); } } -} +} -/* +/* const DOM_filter = /^(SCRIPT|DOM-IF|DOM-REPEAT|svg|SPAN|#text|#comment|yt-icon-shape|iron-iconset-svg)$/; ImprovedTube.childHandler = function (node) { //console.log(node.nodeName); if (DOM_filter.test(node.nodeName)) { return; } var children = node.children; - ImprovedTube.ytElementsHandler(node); + ImprovedTube.ytElementsHandler(node); if (children) { let i = 0; for (const child of children) { @@ -29,7 +29,7 @@ ImprovedTube.childHandler = function (node) { //console.log(node.nodeName); //console.log("node.nodeName:CHILD-"+i+":"+children[i].id+",class:"+children[i].className+","+children[i]+"("+children[i].nodeName+")"); i++; } - } + } }; */ ImprovedTube.ytElementsHandler = function (node) { @@ -42,7 +42,7 @@ ImprovedTube.ytElementsHandler = function (node) { } if (this.storage.blocklist_activate) { // we are interested in thumbnails and video-previews, skip ones with 'button.it-add-to-blocklist' already - if (((node.href && node.classList.contains('ytd-thumbnail')) || node.classList.contains('ytd-video-preview')) + if (((node.href && node.classList.contains('ytd-thumbnail')) || node.classList.contains('ytd-video-preview')) && !node.querySelector("button.it-add-to-blocklist")) { this.blocklistNode(node); } @@ -59,7 +59,7 @@ ImprovedTube.ytElementsHandler = function (node) { try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} catch{try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} catch{try{this.elements.playlist.actions = node.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode;} + catch{try{this.elements.playlist.actions = node.parentNode;} catch{try{this.elements.playlist.actions = node;}catch{}} } } @@ -76,7 +76,7 @@ ImprovedTube.ytElementsHandler = function (node) { try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} catch{try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} catch{try{this.elements.playlist.actions = node.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode;} + catch{try{this.elements.playlist.actions = node.parentNode;} catch{try{this.elements.playlist.actions = node;}catch{}} } } @@ -126,9 +126,9 @@ ImprovedTube.ytElementsHandler = function (node) { } else if (name === 'YTD-MASTHEAD') { if (!this.elements.masthead) { this.elements.masthead = {start: node.querySelector('#start'), - end: node.querySelector('#end'), - logo: node.querySelector('a#logo') - }; + end: node.querySelector('#end'), + logo: node.querySelector('a#logo') + }; this.improvedtubeYoutubeIcon(); } @@ -136,7 +136,7 @@ ImprovedTube.ytElementsHandler = function (node) { else if (name === 'TP-YT-APP-DRAWER') { if (!this.elements.app_drawer) { this.elements.app_drawer = {start: node.querySelector('div#header'), - logo: node.querySelector('a#logo') + logo: node.querySelector('a#logo') }; this.improvedtubeYoutubeIcon(); @@ -190,9 +190,9 @@ ImprovedTube.ytElementsHandler = function (node) { } } }).observe(ImprovedTube.elements.player_thumbnail, {attributes: true, - attributeFilter: ['style'], - childList: false, - subtree: false + attributeFilter: ['style'], + childList: false, + subtree: false }); } } else if (name === 'YTD-WATCH-FLEXY') { @@ -215,12 +215,12 @@ ImprovedTube.ytElementsHandler = function (node) { } return {width: ImprovedTube.elements.player.offsetWidth, - height: Math.round(ImprovedTube.elements.player.offsetWidth / (16 / 9)) + height: Math.round(ImprovedTube.elements.player.offsetWidth / (16 / 9)) }; } return {width: NaN, // ?? - height: NaN + height: NaN }; }; @@ -273,9 +273,9 @@ ImprovedTube.videoPageUpdate = function () { if (this.storage.track_watched_videos === true && video_id) { ImprovedTube.messages.send({action: 'watched', - type: 'add', - id: video_id, - title: document.title + type: 'add', + id: video_id, + title: document.title }); } @@ -329,7 +329,7 @@ ImprovedTube.playerOnPlay = function () { ImprovedTube.initPlayer = function () { if (ImprovedTube.elements.player && ImprovedTube.video_url !== location.href) { - ImprovedTube.video_url = location.href; + ImprovedTube.video_url = location.href; ImprovedTube.user_interacted = false; ImprovedTube.played_before_blur = false; @@ -363,30 +363,30 @@ var noTimeUpdate = null; ImprovedTube.playerOnTimeUpdate = function() { var currentTime = Date.now(); - if (!timeUpdateInterval) { - timeUpdateInterval = setInterval(function() { - if (ImprovedTube.video_src !== this.src) { - ImprovedTube.video_src = this.src; + if (!timeUpdateInterval) { + timeUpdateInterval = setInterval(function() { + if (ImprovedTube.video_src !== this.src) { + ImprovedTube.video_src = this.src; - if (ImprovedTube.initialVideoUpdateDone !== true) { - ImprovedTube.playerQuality(); - } - } else if (ImprovedTube.latestVideoDuration !== this.duration) { - ImprovedTube.latestVideoDuration = this.duration; - + if (ImprovedTube.initialVideoUpdateDone !== true) { ImprovedTube.playerQuality(); } + } else if (ImprovedTube.latestVideoDuration !== this.duration) { + ImprovedTube.latestVideoDuration = this.duration; - if (ImprovedTube.storage.always_show_progress_bar === true) {ImprovedTube.showProgressBar();} - if (ImprovedTube.storage.player_remaining_duration === true){ImprovedTube.playerRemainingDuration();} - ImprovedTube.played_time += .5; - }, 500); - } - clearInterval(noTimeUpdate); - noTimeUpdate = setTimeout(function() { + ImprovedTube.playerQuality(); + } + + if (ImprovedTube.storage.always_show_progress_bar === true) {ImprovedTube.showProgressBar();} + if (ImprovedTube.storage.player_remaining_duration === true){ImprovedTube.playerRemainingDuration();} + ImprovedTube.played_time += .5; + }, 500); + } + clearInterval(noTimeUpdate); + noTimeUpdate = setTimeout(function() { clearInterval(timeUpdateInterval); - timeUpdateInterval = null; - }, 987); + timeUpdateInterval = null; + }, 987); }; ImprovedTube.playerOnLoadedMetadata = function () { @@ -398,23 +398,23 @@ ImprovedTube.playerOnPause = function (event) { if (ImprovedTube.elements.yt_channel_name) { ImprovedTube.messages.send({action: 'analyzer', - name: ImprovedTube.elements.yt_channel_name.__data.tooltipText, - time: ImprovedTube.played_time + name: ImprovedTube.elements.yt_channel_name.__data.tooltipText, + time: ImprovedTube.played_time }); } ImprovedTube.played_time = 0; ImprovedTube.playerControls(); ImprovedTube.playerCinemaModeDisable(); - + }; ImprovedTube.playerOnEnded = function (event) { ImprovedTube.playlistUpNextAutoplay(event); ImprovedTube.messages.send({action: 'analyzer', - //adding "?" (not a fix) - name: ImprovedTube.elements.yt_channel_name?.__data.tooltipText, - time: ImprovedTube.played_time + //adding "?" (not a fix) + name: ImprovedTube.elements.yt_channel_name?.__data.tooltipText, + time: ImprovedTube.played_time }); ImprovedTube.played_time = 0; @@ -429,19 +429,19 @@ ImprovedTube.onkeydown = function () { }, true); }; -ImprovedTube.onmousedown = function () { - window.addEventListener('mousedown', function (event) { +ImprovedTube.onmousedown = function () { + window.addEventListener('mousedown', function (event) { if (!ImprovedTube.user_interacted) { - setTimeout(function(){ImprovedTube.user_interacted = true},3000); + setTimeout(function(){ImprovedTube.user_interacted = true},3000); if (ImprovedTube.elements.player && ImprovedTube.elements.player.classList.contains('ad-showing') === false) { var path = event.composedPath(); for (var i = 0, l = path.length; i < l; i++) { - if (path[i].className - // && path[i].className.indexOf + if (path[i].className + // && path[i].className.indexOf && (/html5-(main-video|video-container)|ytp-play-button/.test(path[i].className)) - ) {ImprovedTube.user_interacted = true;} + ) {ImprovedTube.user_interacted = true;} } - } + } } }, true); }; @@ -534,7 +534,7 @@ ImprovedTube.createIconButton = function (options) { path = document.createElementNS('http://www.w3.org/2000/svg', 'path'), type = this.button_icons[options.type]; - for(const attr of type.svg) svg.setAttribute(attr[0], attr[1]); + for(const attr of type.svg) svg.setAttribute(attr[0], attr[1]); for(const attr of type.path) path.setAttribute(attr[0], attr[1]); svg.appendChild(path); @@ -551,7 +551,7 @@ ImprovedTube.createIconButton = function (options) { event.preventDefault(); event.stopPropagation(); options.onclick.apply(this, arguments); - } + } } else { button.onclick = options.onclick; } @@ -578,8 +578,8 @@ ImprovedTube.createPlayerButton = function (options) { tooltip.style.top = rect.top - 8 + 'px'; tooltip.textContent = this.dataset.title; -if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)){ -tooltip.style.zIndex = 10001;} // needed for cinema mode + if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)){ + tooltip.style.zIndex = 10001;} // needed for cinema mode function mouseleave() { tooltip.remove(); diff --git a/js&css/web-accessible/init.js b/js&css/web-accessible/init.js index 34ea02155..329946a26 100644 --- a/js&css/web-accessible/init.js +++ b/js&css/web-accessible/init.js @@ -83,7 +83,7 @@ if (ImprovedTube.storage.channel_default_tab && ImprovedTube.storage.channel_def ImprovedTube.init = function () { window.addEventListener('yt-page-data-updated', function () { - ImprovedTube.pageType(); + ImprovedTube.pageType(); if (document.documentElement.dataset.pageType === 'video' && /[?&]list=([^&]+).*$/.test(location.href)) { ImprovedTube.playlistRepeat(); ImprovedTube.playlistShuffle(); @@ -109,7 +109,7 @@ ImprovedTube.init = function () { if(this.storage.undo_the_new_sidebar === true){this.undoTheNewSidebar();} if(this.storage.description === "sidebar"){this.descriptionSidebar();} this.channelCompactTheme(); - + if (ImprovedTube.elements.player && ImprovedTube.elements.player.setPlaybackRate) { ImprovedTube.videoPageUpdate(); ImprovedTube.initPlayer(); diff --git a/js&css/web-accessible/www.youtube.com/appearance.js b/js&css/web-accessible/www.youtube.com/appearance.js index 5fde0b5b7..272c26ca4 100644 --- a/js&css/web-accessible/www.youtube.com/appearance.js +++ b/js&css/web-accessible/www.youtube.com/appearance.js @@ -1,23 +1,23 @@ /*------------------------------------------------------------------------------ APPEARANCE ------------------------------------------------------------------------------*/ -ImprovedTube.undoTheNewSidebar = function () { +ImprovedTube.undoTheNewSidebar = function () { if (document.documentElement.dataset.pageType === 'video' && yt) { - try { - yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid = false; - yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = false; + try { + yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid = false; + yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = false; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments_ep = false; yt.config_.EXPERIMENT_FLAGS.web_watch_rounded_player_large = false; } catch (error) { console.error("can't undo description on the side", error); } } }; -ImprovedTube.descriptionSidebar = function () { - try { - yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid = true; - yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = true; +ImprovedTube.descriptionSidebar = function () { + try { + yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid = true; + yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = true; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments_ep = true; - } catch (error) { console.error("tried to move description to the sidebar", error); } + } catch (error) { console.error("tried to move description to the sidebar", error); } }; /*------------------------------------------------------------------------------ PLAYER @@ -26,187 +26,187 @@ ImprovedTube.descriptionSidebar = function () { PLAYER SIZE ------------------------------------------------------------------------------*/ ImprovedTube.playerSize = function () { - if (this.storage.player_size === "custom") { - var width = Number(this.storage.custom_player_size_width) || 1280, - height = Number(this.storage.custom_player_size_height) || 720, - style = this.elements.player_size_style || document.createElement("style"); - - style.textContent = ':root {'; - style.textContent += "--it-player-width:" + width + "px;"; - style.textContent += "--it-player-height:" + height + "px;"; - style.textContent += "}"; - - document.body.appendChild(style); - if (document.documentElement.dataset.pageType === 'video') { window.dispatchEvent(new Event('resize')); } + if (this.storage.player_size === "custom") { + var width = Number(this.storage.custom_player_size_width) || 1280, + height = Number(this.storage.custom_player_size_height) || 720, + style = this.elements.player_size_style || document.createElement("style"); + + style.textContent = ':root {'; + style.textContent += "--it-player-width:" + width + "px;"; + style.textContent += "--it-player-height:" + height + "px;"; + style.textContent += "}"; + + document.body.appendChild(style); + if (document.documentElement.dataset.pageType === 'video') { window.dispatchEvent(new Event('resize')); } } }; /*------------------------------------------------------------------------------ FORCED THEATER MODE ------------------------------------------------------------------------------*/ ImprovedTube.forcedTheaterMode = function () { - if (ImprovedTube.storage.forced_theater_mode === true && ImprovedTube.elements.ytd_watch && ImprovedTube.elements.player) { - var button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); - if (button && ImprovedTube.elements.ytd_watch.theater === false) { - document.cookie = "wide=1;domain=.youtube.com"; - // ImprovedTube.elements.ytd_watch.theater = true; - setTimeout(function () { - button.click(); - }, 100); - } - } + if (ImprovedTube.storage.forced_theater_mode === true && ImprovedTube.elements.ytd_watch && ImprovedTube.elements.player) { + var button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); + if (button && ImprovedTube.elements.ytd_watch.theater === false) { + document.cookie = "wide=1;domain=.youtube.com"; + // ImprovedTube.elements.ytd_watch.theater = true; + setTimeout(function () { + button.click(); + }, 100); + } + } }; /*------------------------------------------------------------------------------ HD THUMBNAIL ------------------------------------------------------------------------------*/ ImprovedTube.playerHdThumbnail = function () { - if (this.storage.player_hd_thumbnail === true) { - var thumbnail = ImprovedTube.elements.player_thumbnail; + if (this.storage.player_hd_thumbnail === true) { + var thumbnail = ImprovedTube.elements.player_thumbnail; - if (thumbnail.style.backgroundImage.indexOf("/hqdefault.jpg") !== -1) { - thumbnail.style.backgroundImage = thumbnail.style.backgroundImage.replace("/hqdefault.jpg", "/maxresdefault.jpg"); - } - } + if (thumbnail.style.backgroundImage.indexOf("/hqdefault.jpg") !== -1) { + thumbnail.style.backgroundImage = thumbnail.style.backgroundImage.replace("/hqdefault.jpg", "/maxresdefault.jpg"); + } + } }; /*------------------------------------------------------------------------------ ALWAYS SHOW PROGRESS BAR ------------------------------------------------------------------------------*/ ImprovedTube.showProgressBar = function () { - - var player = ImprovedTube.elements.player; - - if (player && player.className.indexOf("ytp-autohide") !== -1) { - var played = (player.getCurrentTime() * 100) / player.getDuration(), - loaded = player.getVideoBytesLoaded() * 100, - play_bars = player.querySelectorAll(".ytp-play-progress"), - load_bars = player.querySelectorAll(".ytp-load-progress"), - width = 0, - progress_play = 0, - progress_load = 0; - - for (var i = 0, l = play_bars.length; i < l; i++) { - width += play_bars[i].offsetWidth; - } - var width_percent = width / 100; + var player = ImprovedTube.elements.player; + + if (player && player.className.indexOf("ytp-autohide") !== -1) { + var played = (player.getCurrentTime() * 100) / player.getDuration(), + loaded = player.getVideoBytesLoaded() * 100, + play_bars = player.querySelectorAll(".ytp-play-progress"), + load_bars = player.querySelectorAll(".ytp-load-progress"), + width = 0, + progress_play = 0, + progress_load = 0; - for (var i = 0, l = play_bars.length; i < l; i++) { - var a = play_bars[i].offsetWidth / width_percent, - b = 0, - c = 0; + for (var i = 0, l = play_bars.length; i < l; i++) { + width += play_bars[i].offsetWidth; + } - if (played - progress_play >= a) { - b = 100; - } else if (played > progress_play && played < a + progress_play) { - b = (100 * ((played - progress_play) * width_percent)) / play_bars[i].offsetWidth; - } + var width_percent = width / 100; - play_bars[i].style.transform = "scaleX(" + b / 100 + ")"; + for (var i = 0, l = play_bars.length; i < l; i++) { + var a = play_bars[i].offsetWidth / width_percent, + b = 0, + c = 0; - if (loaded - progress_load >= a) { - c = 100; - } else if (loaded > progress_load && loaded < a + progress_load) { - c = (100 * ((loaded - progress_load) * width_percent)) / play_bars[i].offsetWidth; - } + if (played - progress_play >= a) { + b = 100; + } else if (played > progress_play && played < a + progress_play) { + b = (100 * ((played - progress_play) * width_percent)) / play_bars[i].offsetWidth; + } - load_bars[i].style.transform = "scaleX(" + c / 100 + ")"; + play_bars[i].style.transform = "scaleX(" + b / 100 + ")"; - progress_play += a; - progress_load += a; - } - } + if (loaded - progress_load >= a) { + c = 100; + } else if (loaded > progress_load && loaded < a + progress_load) { + c = (100 * ((loaded - progress_load) * width_percent)) / play_bars[i].offsetWidth; + } + + load_bars[i].style.transform = "scaleX(" + c / 100 + ")"; + + progress_play += a; + progress_load += a; + } + } }; /*------------------------------------------------------------------------------ VIDEO REMAINING DURATION ------------------------------------------------------------------------------*/ ImprovedTube.formatSecond = function (rTime) { - var time = new Date(null); - if (this.storage.duration_with_speed === true) { - var playbackRate = this.elements.video.playbackRate; - time.setSeconds(rTime / playbackRate); - } else { - time.setSeconds(rTime); - } - - if (rTime / 3600 < 1) { - return time.toISOString().substr(14, 5); - } else { - return time.toISOString().substr(11, 8); - } + var time = new Date(null); + if (this.storage.duration_with_speed === true) { + var playbackRate = this.elements.video.playbackRate; + time.setSeconds(rTime / playbackRate); + } else { + time.setSeconds(rTime); + } + + if (rTime / 3600 < 1) { + return time.toISOString().substr(14, 5); + } else { + return time.toISOString().substr(11, 8); + } }; ImprovedTube.playerRemainingDuration = function () { - var player = ImprovedTube.elements.player; - var rTime = ImprovedTube.formatSecond((player.getDuration() - player.getCurrentTime()).toFixed(0)); - var element = document.querySelector(".ytp-time-remaining-duration"); - if (!element) { - var label = document.createElement("span"); - label.textContent = " (-" + rTime + ")"; - label.className = "ytp-time-remaining-duration"; - document.querySelector(".ytp-time-display").appendChild(label); - } else { - element.textContent = " (-" + rTime + ")"; - } + var player = ImprovedTube.elements.player; + var rTime = ImprovedTube.formatSecond((player.getDuration() - player.getCurrentTime()).toFixed(0)); + var element = document.querySelector(".ytp-time-remaining-duration"); + if (!element) { + var label = document.createElement("span"); + label.textContent = " (-" + rTime + ")"; + label.className = "ytp-time-remaining-duration"; + document.querySelector(".ytp-time-display").appendChild(label); + } else { + element.textContent = " (-" + rTime + ")"; + } }; /*------------------------------------------------------------------------------ Comments Sidebar Simple ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebarSimple = function() { if(ImprovedTube.storage.comments_sidebar_simple === true){ - if(window.matchMedia("(min-width: 1599px)").matches) { - document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments"));} - if(window.matchMedia("(max-width: 1598px)").matches) { - document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); - setTimeout(function () { - document.querySelector("#primary-inner").appendChild(document.querySelector("#related"));} - );} - } +ImprovedTube.commentsSidebarSimple = function() { if(ImprovedTube.storage.comments_sidebar_simple === true){ + if(window.matchMedia("(min-width: 1599px)").matches) { + document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments"));} + if(window.matchMedia("(max-width: 1598px)").matches) { + document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); + setTimeout(function () { + document.querySelector("#primary-inner").appendChild(document.querySelector("#related"));} + );} +} } /*------------------------------------------------------------------------------ Comments Sidebar ------------------------------------------------------------------------------*/ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sidebar === true){ - const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); + const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); let hasApplied = 0; - if(/watch\?/.test(location.href)) { - sidebar(); - styleScrollbars(); - setGrid(); - applyObserver(); - window.addEventListener("resize", sidebar) - } + if(/watch\?/.test(location.href)) { + sidebar(); + styleScrollbars(); + setGrid(); + applyObserver(); + window.addEventListener("resize", sidebar) + } function sidebar(){ - resizePlayer(); + resizePlayer(); if(window.matchMedia("(min-width: 1952px)").matches) { if (!hasApplied) { - initialSetup() - setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) + initialSetup() + setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) } else if (hasApplied == 2){ //from medium to big size - setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) - } + setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) + } hasApplied = 1 } - else if(window.matchMedia("(min-width: 1000px)").matches) { + else if(window.matchMedia("(min-width: 1000px)").matches) { if (!hasApplied) { initialSetup(); } else if (hasApplied == 1){ //from big to medium - document.getElementById("primary-inner").appendChild(document.getElementById("related")); + document.getElementById("primary-inner").appendChild(document.getElementById("related")); } hasApplied = 2 } - else { /// <1000 + else { /// <1000 if(hasApplied == 1){ - document.getElementById("primary-inner").appendChild(document.getElementById("related")); - let comments = document.querySelector("#comments"); - let below = document.getElementById("below"); - below.appendChild(comments); + document.getElementById("primary-inner").appendChild(document.getElementById("related")); + let comments = document.querySelector("#comments"); + let below = document.getElementById("below"); + below.appendChild(comments); } else if (hasApplied == 2){ - let comments = document.querySelector("#comments"); - let below = document.getElementById("below"); - below.appendChild(comments); + let comments = document.querySelector("#comments"); + let below = document.getElementById("below"); + below.appendChild(comments); } hasApplied = 0; } @@ -215,39 +215,39 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid let checkParentInterval = setInterval(() => { container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; if (container) { - clearInterval(checkParentInterval); - container.style.display = "flex"; - container.style.flexWrap = "wrap"; - container.style.flexDirection = "row"; + clearInterval(checkParentInterval); + container.style.display = "flex"; + container.style.flexWrap = "wrap"; + container.style.flexDirection = "row"; } }, 250); } - function initialSetup() { - let secondaryInner = document.getElementById("secondary-inner"); - let primaryInner = document.getElementById("primary-inner"); - let comments = document.querySelector("#comments"); - setTimeout(() => { - primaryInner.appendChild(document.getElementById("panels")); - primaryInner.appendChild(document.getElementById("related")) - secondaryInner.appendChild(document.getElementById("chat-template")); - secondaryInner.appendChild(comments); - }) - } - function resizePlayer() { - const width = video.offsetWidth + 24; - const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); - document.getElementById("primary").style.width = `${width}px`; - player.style.width = `${width}px`; - } - function styleScrollbars(){ - if (!navigator.userAgent.toLowerCase().includes("mac")){ - let color, colorHover - const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; - if(isDarkMode) [color,colorHover] = ["#616161", "#909090"]; - else [color,colorHover] = ["#aaaaaa", "#717171"]; - const style = document.createElement("style"); + function initialSetup() { + let secondaryInner = document.getElementById("secondary-inner"); + let primaryInner = document.getElementById("primary-inner"); + let comments = document.querySelector("#comments"); + setTimeout(() => { + primaryInner.appendChild(document.getElementById("panels")); + primaryInner.appendChild(document.getElementById("related")) + secondaryInner.appendChild(document.getElementById("chat-template")); + secondaryInner.appendChild(comments); + }) + } + function resizePlayer() { + const width = video.offsetWidth + 24; + const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); + document.getElementById("primary").style.width = `${width}px`; + player.style.width = `${width}px`; + } + function styleScrollbars(){ + if (!navigator.userAgent.toLowerCase().includes("mac")){ + let color, colorHover + const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; + if(isDarkMode) [color,colorHover] = ["#616161", "#909090"]; + else [color,colorHover] = ["#aaaaaa", "#717171"]; + const style = document.createElement("style"); if(ImprovedTube.storage.comments_sidebar_scrollbars === true){ - const cssRule = ` + const cssRule = ` #primary, #secondary { overflow: overlay !important; } @@ -268,8 +268,8 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid ::-webkit-scrollbar-thumb:hover{ background-color: ${colorHover}; }`; - style.appendChild(document.createTextNode(cssRule)); - } + style.appendChild(document.createTextNode(cssRule)); + } else { const cssRule = ` #primary, #secondary { overflow: overlay !important; @@ -278,27 +278,27 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid { width: 0px; height: 0px; - }`; + }`; style.appendChild(document.createTextNode(cssRule)); - } - document.head.appendChild(style); - } - } - function applyObserver(){ - const debouncedResizePlayer = debounce(resizePlayer, 200); - const resizeObserver = new ResizeObserver(debouncedResizePlayer); - resizeObserver.observe(video); - } - function debounce(callback, delay) { - let timerId; - return function (...args) { - clearTimeout(timerId); - timerId = setTimeout(() => { - callback.apply(this, args); - }, delay); - }; - } - } + } + document.head.appendChild(style); + } + } + function applyObserver(){ + const debouncedResizePlayer = debounce(resizePlayer, 200); + const resizeObserver = new ResizeObserver(debouncedResizePlayer); + resizeObserver.observe(video); + } + function debounce(callback, delay) { + let timerId; + return function (...args) { + clearTimeout(timerId); + timerId = setTimeout(() => { + callback.apply(this, args); + }, delay); + }; + } +} } /*------------------------------------------------------------------------------ SIDEBAR @@ -307,27 +307,27 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid TRANSCRIPT --------------------------------------------------------------*/ ImprovedTube.transcript = function (el){ if (ImprovedTube.storage.transcript === true){ -el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility');} } + el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility');} } /*---------------------------------------------------------------- CHAPTERS --------------------------------------------------------------*/ ImprovedTube.chapters = function (el){ if (ImprovedTube.storage.chapters === true){ -el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility');} } + el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility');} } /*------------------------------------------------------------------------------ LIVECHAT ------------------------------------------------------------------------------*/ ImprovedTube.livechat = function () { - if (this.storage.livechat === "collapsed") { - if (typeof isCollapsed === 'undefined') { var isCollapsed = false; } - if(ImprovedTube.elements.livechat && !isCollapsed){ - ImprovedTube.elements.livechat.button.click(); - isCollapsed = true - } - } /* else{ + if (this.storage.livechat === "collapsed") { + if (typeof isCollapsed === 'undefined') { var isCollapsed = false; } + if(ImprovedTube.elements.livechat && !isCollapsed){ + ImprovedTube.elements.livechat.button.click(); + isCollapsed = true + } + } /* else{ if(isCollapsed){ ImprovedTube.elements.livechat.button.click(); isCollapsed = false - } + } } */ }; /*------------------------------------------------------------------------------ @@ -340,101 +340,101 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { if (window.self !== window.top) { return false; } if (document.documentElement.dataset.pageType === 'video') { - var section = document.querySelector('#subscribe-button'); - /* if (this.storage.description == "classic" + var section = document.querySelector('#subscribe-button'); + /* if (this.storage.description == "classic" || this.storage.description == "classic_expanded" || this.storage.description == "classic_hidden" ) {var section = document.querySelector('#flex.ytd-video-primary-info-renderer');} */ - if (section && !section.querySelector('.improvedtube-player-button')) { - if (this.storage.below_player_loop !== false) { - var button = document.createElement('button'), - svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), - path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + if (section && !section.querySelector('.improvedtube-player-button')) { + if (this.storage.below_player_loop !== false) { + var button = document.createElement('button'), + svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), + path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); var transparentOrOn = .5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } - button.className = 'improvedtube-player-button'; - button.id = 'it-below-player-loop'; - button.dataset.tooltip = 'Loop'; - svg.style.opacity = transparentOrOn; - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z'); - - button.onclick = function () { - var video = ImprovedTube.elements.video, - svg = this.children[0]; - - function matchLoopState(opacity) { + button.className = 'improvedtube-player-button'; + button.id = 'it-below-player-loop'; + button.dataset.tooltip = 'Loop'; + svg.style.opacity = transparentOrOn; + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z'); + + button.onclick = function () { + var video = ImprovedTube.elements.video, + svg = this.children[0]; + + function matchLoopState(opacity) { svg.style.opacity = opacity; - if (ImprovedTube.storage.player_repeat_button === true) { + if (ImprovedTube.storage.player_repeat_button === true) { var otherButton = document.querySelector('#it-repeat-button'); otherButton.style.opacity = opacity; } } - if (video.hasAttribute('loop')) { - video.removeAttribute('loop'); - matchLoopState('.5') - } else if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { - video.setAttribute('loop', ''); - matchLoopState('1') - } - }; - - svg.appendChild(path); button.appendChild(svg); - section.insertAdjacentElement('afterend', button) - } + if (video.hasAttribute('loop')) { + video.removeAttribute('loop'); + matchLoopState('.5') + } else if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { + video.setAttribute('loop', ''); + matchLoopState('1') + } + }; + + svg.appendChild(path); button.appendChild(svg); + section.insertAdjacentElement('afterend', button) + } if (this.storage.below_player_pip !== false) { - var button = document.createElement('button'), - svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), - path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - - button.className = 'improvedtube-player-button'; - button.dataset.tooltip = 'PiP'; - svg.style.opacity = '.64'; - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - path.setAttributeNS(null, 'd', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z'); - - button.onclick = function () { - var video = document.querySelector('#movie_player video'); - if (video) {video.requestPictureInPicture();} - }; - - svg.appendChild(path); button.appendChild(svg); - section.insertAdjacentElement('afterend', button) - } - + var button = document.createElement('button'), + svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), + path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + + button.className = 'improvedtube-player-button'; + button.dataset.tooltip = 'PiP'; + svg.style.opacity = '.64'; + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + path.setAttributeNS(null, 'd', 'M19 7h-8v6h8V7zm2-4H3C2 3 1 4 1 5v14c0 1 1 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zm0 16H3V5h18v14z'); + + button.onclick = function () { + var video = document.querySelector('#movie_player video'); + if (video) {video.requestPictureInPicture();} + }; + + svg.appendChild(path); button.appendChild(svg); + section.insertAdjacentElement('afterend', button) + } + if (this.storage.below_player_screenshot !== false) { - var button = document.createElement('button'), - svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), - path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - - button.className = 'improvedtube-player-button'; - button.dataset.tooltip = 'Screenshot'; - svg.style.opacity = '.55'; - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - path.setAttributeNS(null, 'd', 'M21 19V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z'); - - button.onclick = ImprovedTube.screenshot; - - svg.appendChild(path); button.appendChild(svg); - section.insertAdjacentElement('afterend', button) - } + var button = document.createElement('button'), + svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), + path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + + button.className = 'improvedtube-player-button'; + button.dataset.tooltip = 'Screenshot'; + svg.style.opacity = '.55'; + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + path.setAttributeNS(null, 'd', 'M21 19V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z'); + + button.onclick = ImprovedTube.screenshot; + + svg.appendChild(path); button.appendChild(svg); + section.insertAdjacentElement('afterend', button) + } } - } + } }; /*------------------------------------------------------------------------------ EXPAND DESCRIPTION ------------------------------------------------------------------------------*/ -ImprovedTube.expandDescription = function (el) { - if (this.storage.description === "expanded" || this.storage.description === "classic_expanded") { - if (el) {el.click(); setTimeout(function(){ImprovedTube.elements.player.focus();}, 1200); } - else { var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} - // ...except when it is an embedded player? - var waitForDescription = setInterval(() => { - if (++tries >= maxTries) { - el = document.querySelector('#description-inline-expander') - if ( el) { el.click(); setTimeout(function(){ImprovedTube.elements.player.focus(); }, 1200);clearInterval(waitForDescription); } - intervalMs *= 1.11; }}, intervalMs); - } - } +ImprovedTube.expandDescription = function (el) { + if (this.storage.description === "expanded" || this.storage.description === "classic_expanded") { + if (el) {el.click(); setTimeout(function(){ImprovedTube.elements.player.focus();}, 1200); } + else { var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} + // ...except when it is an embedded player? + var waitForDescription = setInterval(() => { + if (++tries >= maxTries) { + el = document.querySelector('#description-inline-expander') + if ( el) { el.click(); setTimeout(function(){ImprovedTube.elements.player.focus(); }, 1200);clearInterval(waitForDescription); } + intervalMs *= 1.11; }}, intervalMs); + } + } } /*------------------------------------------------------------------------------ HIDE DETAIL BUTTON @@ -453,181 +453,181 @@ ImprovedTube.expandDescription = function (el) { /*-------------------------------------------------------------- DAY OF WEEK --------------------------------------------------------------*/ -ImprovedTube.dayOfWeek = function () { if (this.storage.day_of_week === true) { - var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; - setTimeout(function () { - var videoDate; try { videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate } //YouTube related video or internal link? - catch { try { videoDate = document.querySelector("[itemprop=datePublished]").content;} catch { } } //..no? must be new session? - var tempDate = new Date(videoDate); - var element = document.querySelector(".ytd-day-of-week"); - if (!element) { - var label = document.createElement("span"); - label.textContent = days[tempDate.getDay() + 1] + ' '; - label.className = "ytd-day-of-week"; - //update please: - try {document.querySelector("#info span:nth-child(2)")?.append(label);} catch { try {document.querySelector("#info #info-strings yt-formatted-string")?.append(label);}catch {}} - } // else { element.textContent = days[tempDate.getDay() + 1] + ", "; } - }, 4321); - } +ImprovedTube.dayOfWeek = function () { if (this.storage.day_of_week === true) { + var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; + setTimeout(function () { + var videoDate; try { videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate } //YouTube related video or internal link? + catch { try { videoDate = document.querySelector("[itemprop=datePublished]").content;} catch { } } //..no? must be new session? + var tempDate = new Date(videoDate); + var element = document.querySelector(".ytd-day-of-week"); + if (!element) { + var label = document.createElement("span"); + label.textContent = days[tempDate.getDay() + 1] + ' '; + label.className = "ytd-day-of-week"; + //update please: + try {document.querySelector("#info span:nth-child(2)")?.append(label);} catch { try {document.querySelector("#info #info-strings yt-formatted-string")?.append(label);}catch {}} + } // else { element.textContent = days[tempDate.getDay() + 1] + ", "; } + }, 4321); +} }; /*------------------------------------------------------------------------------ HOW LONG AGO THE VIDEO WAS UPLOADED ------------------------------------------------------------------------------*/ ImprovedTube.howLongAgoTheVideoWasUploaded = function () { - if (this.storage.how_long_ago_the_video_was_uploaded === true && this.elements.yt_channel_name) { - var xhr = new XMLHttpRequest(), - key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey, - id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); + if (this.storage.how_long_ago_the_video_was_uploaded === true && this.elements.yt_channel_name) { + var xhr = new XMLHttpRequest(), + key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey, + id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); - function timeSince(date) { - var seconds = Math.floor((new Date() - new Date(date)) / 1000), - interval = Math.floor(seconds / 31536000); + function timeSince(date) { + var seconds = Math.floor((new Date() - new Date(date)) / 1000), + interval = Math.floor(seconds / 31536000); - if (interval > 1) { - return interval + " years ago"; - } - interval = Math.floor(seconds / 2592000); - if (interval > 1) { - return interval + " months ago"; - } - interval = Math.floor(seconds / 86400); - if (interval > 1) { - return interval + " days ago"; - } - interval = Math.floor(seconds / 3600); - if (interval > 1) { - return interval + " hours ago"; - } - interval = Math.floor(seconds / 60); - if (interval > 1) { - return interval + " minutes ago"; - } + if (interval > 1) { + return interval + " years ago"; + } + interval = Math.floor(seconds / 2592000); + if (interval > 1) { + return interval + " months ago"; + } + interval = Math.floor(seconds / 86400); + if (interval > 1) { + return interval + " days ago"; + } + interval = Math.floor(seconds / 3600); + if (interval > 1) { + return interval + " hours ago"; + } + interval = Math.floor(seconds / 60); + if (interval > 1) { + return interval + " minutes ago"; + } - return Math.floor(seconds) + " seconds ago"; - } + return Math.floor(seconds) + " seconds ago"; + } - xhr.addEventListener("load", function () { - var response = JSON.parse(this.responseText), - element = ImprovedTube.elements.how_long_ago_the_video_was_uploaded || document.createElement("div"); + xhr.addEventListener("load", function () { + var response = JSON.parse(this.responseText), + element = ImprovedTube.elements.how_long_ago_the_video_was_uploaded || document.createElement("div"); - ImprovedTube.empty(element); + ImprovedTube.empty(element); - if (response.error) { - element.appendChild(document.createTextNode("• Error: " + response.error.code)); - } else { - element.appendChild(document.createTextNode("• " + timeSince(response.items[0].snippet.publishedAt))); - } + if (response.error) { + element.appendChild(document.createTextNode("• Error: " + response.error.code)); + } else { + element.appendChild(document.createTextNode("• " + timeSince(response.items[0].snippet.publishedAt))); + } - element.className = "it-how-long-ago-the-video-was-uploaded"; + element.className = "it-how-long-ago-the-video-was-uploaded"; - ImprovedTube.elements.how_long_ago_the_video_was_uploaded = element; + ImprovedTube.elements.how_long_ago_the_video_was_uploaded = element; - document.querySelector("#info #info-text").appendChild(element); - }); + document.querySelector("#info #info-text").appendChild(element); + }); - xhr.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + id + "&key=" + key, true); - xhr.send(); - } + xhr.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + id + "&key=" + key, true); + xhr.send(); + } }; /*------------------------------------------------------------------------------ SHOW CHANNEL VIDEOS COUNT ------------------------------------------------------------------------------*/ ImprovedTube.channelVideosCount = function () { - if (this.storage.channel_videos_count === true && this.elements.yt_channel_link) { - var key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey; - if (this.elements.yt_channel_link.href.indexOf("/channel/") == -1) { - var xhr = new XMLHttpRequest(), - id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); - xhr.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + id + "&key=" + key, false); - xhr.send(); - if (xhr.readyState === xhr.DONE && xhr.status === 200) { - var response = JSON.parse(xhr.responseText); - id = response.items[0].snippet.channelId; - } - } else { - id = this.elements.yt_channel_link.href.slice(this.elements.yt_channel_link.href.indexOf("/channel/") + "/channel/".length); - if (id.indexOf("/") !== -1) { - id = id.match(/.+?(?=\/)/)[0]; - } - } + if (this.storage.channel_videos_count === true && this.elements.yt_channel_link) { + var key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey; + if (this.elements.yt_channel_link.href.indexOf("/channel/") == -1) { + var xhr = new XMLHttpRequest(), + id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); + xhr.open("GET", "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + id + "&key=" + key, false); + xhr.send(); + if (xhr.readyState === xhr.DONE && xhr.status === 200) { + var response = JSON.parse(xhr.responseText); + id = response.items[0].snippet.channelId; + } + } else { + id = this.elements.yt_channel_link.href.slice(this.elements.yt_channel_link.href.indexOf("/channel/") + "/channel/".length); + if (id.indexOf("/") !== -1) { + id = id.match(/.+?(?=\/)/)[0]; + } + } - xhr = new XMLHttpRequest(); + xhr = new XMLHttpRequest(); - xhr.addEventListener("load", function () { - var response = JSON.parse(this.responseText), - parent = document.querySelector("#meta ytd-channel-name + yt-formatted-string"), - element = ImprovedTube.elements.channel_videos_count || document.createElement("div"); + xhr.addEventListener("load", function () { + var response = JSON.parse(this.responseText), + parent = document.querySelector("#meta ytd-channel-name + yt-formatted-string"), + element = ImprovedTube.elements.channel_videos_count || document.createElement("div"); - ImprovedTube.empty(element); + ImprovedTube.empty(element); - if (response.error) { - element.appendChild(document.createTextNode("• Error: " + response.error.code)); - } else { - element.appendChild(document.createTextNode("• " + response.items[0].statistics.videoCount + " videos")); - } + if (response.error) { + element.appendChild(document.createTextNode("• Error: " + response.error.code)); + } else { + element.appendChild(document.createTextNode("• " + response.items[0].statistics.videoCount + " videos")); + } - element.className = "it-channel-videos-count"; + element.className = "it-channel-videos-count"; - ImprovedTube.elements.channel_videos_count = element; + ImprovedTube.elements.channel_videos_count = element; - parent.appendChild(element); + parent.appendChild(element); - ImprovedTube.elements.channel_videos_count = element; - }); + ImprovedTube.elements.channel_videos_count = element; + }); - xhr.open("GET", "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + id + "&key=" + key, true); - xhr.send(); - } + xhr.open("GET", "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=" + id + "&key=" + key, true); + xhr.send(); + } }; if (ImprovedTube.storage.header_transparent2 === true) { - /*------------------------------------------------------------------------------ + /*------------------------------------------------------------------------------ TURN TOP BAR TRANSPARENT WHEN SCROLLING ------------------------------------------------------------------------------*/ - window.addEventListener('scroll', function () { - var masthead = document.querySelector('html[it-header-transparent=true] ytd-masthead'); - var endButtons = masthead.querySelector('#end'); - - if (window.scrollY === 0) { - endButtons.style.visibility = 'visible'; - } else { - endButtons.style.visibility = 'hidden'; - } - }); + window.addEventListener('scroll', function () { + var masthead = document.querySelector('html[it-header-transparent=true] ytd-masthead'); + var endButtons = masthead.querySelector('#end'); + + if (window.scrollY === 0) { + endButtons.style.visibility = 'visible'; + } else { + endButtons.style.visibility = 'hidden'; + } + }); - function handleScroll() { - var scrollTop = window.pageYOffset || document.documentElement.scrollTop; - var buttonsContainer = document.getElementById('buttons'); + function handleScroll() { + var scrollTop = window.pageYOffset || document.documentElement.scrollTop; + var buttonsContainer = document.getElementById('buttons'); - if (scrollTop > 100) { - buttonsContainer.classList.add('hidden'); - } else { - buttonsContainer.classList.remove('hidden'); - } - } + if (scrollTop > 100) { + buttonsContainer.classList.add('hidden'); + } else { + buttonsContainer.classList.remove('hidden'); + } + } - /*------------------------------------------------------------------------------ + /*------------------------------------------------------------------------------ CHECK IF USER IS SCROLLING ------------------------------------------------------------------------------*/ - window.addEventListener("scroll", handleScroll); - - function getScrollDirection() { - var lastScrollTop = 0; - return function() { - var st = window.pageYOffset || document.documentElement.scrollTop; - var scrollDirection = st > lastScrollTop ? 'down' : 'up'; - lastScrollTop = st <= 0 ? 0 : st; - return scrollDirection; - }; - } - - var scrollDirection = getScrollDirection(); - - window.addEventListener('scroll', function() { - var direction = scrollDirection(); - if (direction === 'down') { - document.documentElement.setAttribute('data-scroll-direction', 'down'); - } else { - document.documentElement.removeAttribute('data-scroll-direction'); - } - }); + window.addEventListener("scroll", handleScroll); + + function getScrollDirection() { + var lastScrollTop = 0; + return function() { + var st = window.pageYOffset || document.documentElement.scrollTop; + var scrollDirection = st > lastScrollTop ? 'down' : 'up'; + lastScrollTop = st <= 0 ? 0 : st; + return scrollDirection; + }; + } + + var scrollDirection = getScrollDirection(); + + window.addEventListener('scroll', function() { + var direction = scrollDirection(); + if (direction === 'down') { + document.documentElement.setAttribute('data-scroll-direction', 'down'); + } else { + document.documentElement.removeAttribute('data-scroll-direction'); + } + }); } diff --git a/js&css/web-accessible/www.youtube.com/blocklist.js b/js&css/web-accessible/www.youtube.com/blocklist.js index 9e61c6c58..2d9f20bcc 100644 --- a/js&css/web-accessible/www.youtube.com/blocklist.js +++ b/js&css/web-accessible/www.youtube.com/blocklist.js @@ -13,7 +13,7 @@ ImprovedTube.blocklistNode = function (node) { // YT reuses Thumbnail cells dynamically, need to monitor all created Thumbnail links and dynamically apply/remove 'it-blocklisted-*' classes if (!this.elements.observerList.includes(node)) { this.blocklistObserver.observe(node, {attributes: true, - attributeFilter: ['href']}); + attributeFilter: ['href']}); // keeping a list to attach only one observer per tracked element this.elements.observerList.push(node); } @@ -77,12 +77,12 @@ ImprovedTube.blocklistNode = function (node) { // this message will trigger 'storage-changed' event and eventually blocklistInit() full rescan ImprovedTube.messages.send({action: 'blocklist', - added: added, - type: type, - id: type == 'channel' ? channel : video, - title: title, - when: Date.parse(new Date().toDateString()) / 100000 - }); + added: added, + type: type, + id: type == 'channel' ? channel : video, + title: title, + when: Date.parse(new Date().toDateString()) / 100000 + }); } }); @@ -128,13 +128,13 @@ ImprovedTube.blocklistChannel = function (node) { // this message will trigger 'storage-changed' event and eventually blocklistInit() full rescan ImprovedTube.messages.send({action: 'blocklist', - added: !ImprovedTube.storage.blocklist.channels[id], - type: 'channel', - id: id, - title: title, - preview: preview, - when: Date.parse(new Date().toDateString()) / 100000 - }); + added: !ImprovedTube.storage.blocklist.channels[id], + type: 'channel', + id: id, + title: title, + preview: preview, + when: Date.parse(new Date().toDateString()) / 100000 + }); }; node.parentNode.parentNode.appendChild(button); diff --git a/js&css/web-accessible/www.youtube.com/channel.js b/js&css/web-accessible/www.youtube.com/channel.js index e4db1aa78..3eb3aa87c 100644 --- a/js&css/web-accessible/www.youtube.com/channel.js +++ b/js&css/web-accessible/www.youtube.com/channel.js @@ -26,7 +26,7 @@ ImprovedTube.channelDefaultTab = function (a) { ImprovedTube.channelPlayAllButton = function () { if (ImprovedTube.regex.channel.test(location.pathname)) { if (this.storage.channel_play_all_button) { - const container = document.querySelector('ytd-channel-sub-menu-renderer #primary-items') + const container = document.querySelector('ytd-channel-sub-menu-renderer #primary-items') || document.querySelector('ytd-two-column-browse-results-renderer #chips-content'), playlistUrl = document.querySelector('ytd-app')?.__data?.data?.response?.metadata?.channelMetadataRenderer?.externalId?.substring(2); @@ -36,11 +36,11 @@ ImprovedTube.channelPlayAllButton = function () { return; } const button = this.createIconButton({ - type: 'playAll', - className: 'it-play-all-button', - text: 'Play all', - href: '/playlist?list=UU' + playlistUrl - }); + type: 'playAll', + className: 'it-play-all-button', + text: 'Play all', + href: '/playlist?list=UU' + playlistUrl + }); container.appendChild(button); } else { document.querySelector('.it-play-all-button')?.remove(); @@ -55,15 +55,15 @@ var compact = compact || {} ImprovedTube.channelCompactTheme = function () { compact.eventHandlerFns = compact.eventHandlerFns || [] compact.styles = compact.styles || [] - if (this.storage.channel_compact_theme === true) { + if (this.storage.channel_compact_theme === true) { compact.hasApplied = true initialLoad(); document.querySelector("#sections #items") ? styleWithListeners() : styleWithInterval(); - } + } else if (compact.hasApplied) { //cleanup - try {clearInterval(compact.listener)} + try {clearInterval(compact.listener)} catch (err) {console.log("ERR: We couldn't clear listener. Reload page")} - if (compact.eventHandlerFns.length) removeListeners(); + if (compact.eventHandlerFns.length) removeListeners(); if (compact.styles.length) removeStyles() compact = {} } @@ -105,8 +105,8 @@ ImprovedTube.channelCompactTheme = function () { } removeStyles(); } - - function removeListeners(){ // EventListeners + + function removeListeners(){ // EventListeners for (let i = 0; i <= 2; i++) { const parent = compact.parents[i] const sub = compact.subs[i] @@ -117,26 +117,26 @@ ImprovedTube.channelCompactTheme = function () { } function initialLoad() { - for (let i = 0; i <= 2; i++) { - let isCompact = localStorage.getItem(`ImprovedTube-compact-${i + 2}`) === "true" + for (let i = 0; i <= 2; i++) { + let isCompact = localStorage.getItem(`ImprovedTube-compact-${i + 2}`) === "true" isCompact ? appendStyle(i) : (compact.styles[i] = null); - } - } + } + } - function appendStyle(index) { // adds style tag - const cssRules = ` + function appendStyle(index) { // adds style tag + const cssRules = ` #sections > ytd-guide-section-renderer:nth-child(${index + 2}) > #items{ display:none; };`; - const style = document.createElement("style"); - style.appendChild(document.createTextNode(cssRules)); - compact.styles[index] = style; - document.head.appendChild(compact.styles[index]); - } + const style = document.createElement("style"); + style.appendChild(document.createTextNode(cssRules)); + compact.styles[index] = style; + document.head.appendChild(compact.styles[index]); + } function removeStyles(){ // styles tags for (let i = 0; i <= compact.styles.length; i++){ - if (compact.styles[i] && compact.styles[i].parentNode) { + if (compact.styles[i] && compact.styles[i].parentNode) { document.head.removeChild(compact.styles[i]); } } diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index 0bada3ba5..f3aab0e5e 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -17,7 +17,7 @@ ImprovedTube.autoplayDisable = function (videoElement) { // no ads playing && !player.classList.contains('ad-showing') // video page - && ((location.href.includes('/watch?') // #1703 + && ((location.href.includes('/watch?') // #1703 // player_autoplay_disable & not playlist && (this.storage.player_autoplay_disable && !location.href.includes('list=')) // !playlist_autoplay & playlist @@ -42,7 +42,7 @@ ImprovedTube.forcedPlayVideoFromTheBeginning = function () { const player = this.elements.player, video = this.elements.video, paused = video?.paused; - + if (player && video && this.storage.forced_play_video_from_the_beginning && location.pathname == '/watch') { player.seekTo(0); // restore previous paused state @@ -80,7 +80,7 @@ ImprovedTube.playerAutoPip = function () { console.error('Failed to enter Picture-in-Picture mode', error); } })(); - } + } }; /*------------------------------------------------------------------------------ PLAYBACK SPEED @@ -97,7 +97,7 @@ ImprovedTube.playbackSpeed = function (newSpeed) { // called with no option or demanded speed already set, only provide readback if (!newSpeed || speed == newSpeed) return speed; - + if (video?.playbackRate) { video.playbackRate = newSpeed; newSpeed = video.playbackRate; @@ -112,128 +112,128 @@ ImprovedTube.playbackSpeed = function (newSpeed) { FORCED PLAYBACK SPEED ------------------------------------------------------------------------------*/ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_playback_speed === true) { - var player = this.elements.player, + var player = this.elements.player, video = player.querySelector('video'), option = this.storage.player_playback_speed; - if (this.isset(option) === false) { option = 1; } - else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) ) + if (this.isset(option) === false) { option = 1; } + else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) ) { console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; } - if ( !player.getVideoData().isLive || player.getVideoData().isLive === false) -{ player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl - if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true) + if ( !player.getVideoData().isLive || player.getVideoData().isLive === false) + { player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl + if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true) && option !== 1) { -ImprovedTube.speedException = function () { -if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education') - {player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return;} -if (this.storage.player_force_speed_on_music === true) - { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); + ImprovedTube.speedException = function () { + if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education') + {player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return;} + if (this.storage.player_force_speed_on_music === true) + { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); return;} -if (DATA.keywords && !keywords) { keywords = DATA.keywords.join(', ') || ''; } -if (keywords === 'video, sharing, camera phone, video phone, free, upload') { keywords = ''; } -var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i; -var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i; -var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i"); -var musicRegexMatch = musicIdentifiersTitle.test(DATA.title); - if (!musicRegexMatch) { - var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i; - var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i"); + if (DATA.keywords && !keywords) { keywords = DATA.keywords.join(', ') || ''; } + if (keywords === 'video, sharing, camera phone, video phone, free, upload') { keywords = ''; } + var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i; + var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i; + var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i"); + var musicRegexMatch = musicIdentifiersTitle.test(DATA.title); + if (!musicRegexMatch) { + var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i; + var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i"); keywordsAmount = 1 + ((keywords || '').match(/,/) || []).length; - if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) { - musicRegexMatch = true}} -notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); - // (Tags/keywords shouldnt lie & very few songs titles might have these words) - if (DATA.duration) { - function parseDuration(duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); - return h * 3600 + m * 60 + s; } - DATA.lengthSeconds = parseDuration(DATA.duration); } - function testSongDuration(s, ytMusic) { - if (135 <= s && s <= 260) {return 'veryCommon';} - if (105 <= s && s <= 420) {return 'common';} - if (420 <= s && s <= 720) {return 'long';} - if (45 <= s && s <= 105) {return 'short';} - if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) {return 'multiple';} + if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) { + musicRegexMatch = true}} + notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); + // (Tags/keywords shouldnt lie & very few songs titles might have these words) + if (DATA.duration) { + function parseDuration(duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); + return h * 3600 + m * 60 + s; } + DATA.lengthSeconds = parseDuration(DATA.duration); } + function testSongDuration(s, ytMusic) { + if (135 <= s && s <= 260) {return 'veryCommon';} + if (105 <= s && s <= 420) {return 'common';} + if (420 <= s && s <= 720) {return 'long';} + if (45 <= s && s <= 105) {return 'short';} + if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) {return 'multiple';} //does Youtube ever show more than 10 songs below the description? - } -var songDurationType = testSongDuration(DATA.lengthSeconds); -console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType); - // check if the video is PROBABLY MUSIC: - if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon')) - || ( musicRegexMatch && !notMusicRegexMatch && (typeof songDurationType !== 'undefined' - || (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords) + } + var songDurationType = testSongDuration(DATA.lengthSeconds); + console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType); + // check if the video is PROBABLY MUSIC: + if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon')) + || ( musicRegexMatch && !notMusicRegexMatch && (typeof songDurationType !== 'undefined' + || (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords) && 1000 <= DATA.lengthSeconds )) ) // && 1150 <= DATA.lengthSeconds <= 5000 - || ( DATA.genre === 'Music' && musicRegexMatch && (typeof songDurationType !== 'undefined' - || (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords) + || ( DATA.genre === 'Music' && musicRegexMatch && (typeof songDurationType !== 'undefined' + || (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords) && 1000 <= DATA.lengthSeconds )) ) // && DATA.lengthSeconds <= 5000 - || (amountOfSongs && testSongDuration(DATA.lengthSeconds, amountOfSongs ) !== 'undefined') + || (amountOfSongs && testSongDuration(DATA.lengthSeconds, amountOfSongs ) !== 'undefined') // || location.href.indexOf('music.') !== -1 // (=currently we are only running on www.youtube.com anyways) - ) { player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); } - else { // Now this video might rarely be music + ) { player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); } + else { // Now this video might rarely be music // - however we can make extra-sure after waiting for the video descripion to load... (#1539) - var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} - // ...except when it is an embedded player? - var waitForDescription = setInterval(() => { - if (++tries >= maxTries) { - subtitle = document.querySelector('#title + #subtitle:last-of-type') - if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs) + var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} + // ...except when it is an embedded player? + var waitForDescription = setInterval(() => { + if (++tries >= maxTries) { + subtitle = document.querySelector('#title + #subtitle:last-of-type') + if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs) && typeof testSongDuration(DATA.lengthSeconds, Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) ) !== 'undefined' ) // resonable duration - {player.setPlaybackRate(1); video.playbackRate = 1; console.log("...but YouTube shows music below the description!"); clearInterval(waitForDescription); } - intervalMs *= 1.11; }}, intervalMs); - window.addEventListener('load', () => { setTimeout(() => { clearInterval(waitForDescription); }, 1234); }); - } - } -//DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere) -DATA = {}; -defaultKeywords = "video,sharing,camera,phone,video phone,free,upload"; -DATA.keywords = false; keywords = false; amountOfSongs = false; -DATA.videoID = ImprovedTube.videoId() || false; - ImprovedTube.fetchDOMData = function () { + {player.setPlaybackRate(1); video.playbackRate = 1; console.log("...but YouTube shows music below the description!"); clearInterval(waitForDescription); } + intervalMs *= 1.11; }}, intervalMs); + window.addEventListener('load', () => { setTimeout(() => { clearInterval(waitForDescription); }, 1234); }); + } + } + //DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere) + DATA = {}; + defaultKeywords = "video,sharing,camera,phone,video phone,free,upload"; + DATA.keywords = false; keywords = false; amountOfSongs = false; + DATA.videoID = ImprovedTube.videoId() || false; + ImprovedTube.fetchDOMData = function () { // if (history.length > 1 && history.state.endpoint.watchEndpoint) { - try { DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name;} - catch { DATA.genre = false; DATA.keywords = false; DATA.lengthSeconds = false; - try { - DATA.title = document.getElementsByTagName('meta')?.title?.content || false; - DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; - DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; - } catch {}} if ( DATA.title === ImprovedTube.videoTitle() ) + try { DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name;} + catch { DATA.genre = false; DATA.keywords = false; DATA.lengthSeconds = false; + try { + DATA.title = document.getElementsByTagName('meta')?.title?.content || false; + DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; + DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; + } catch {}} if ( DATA.title === ImprovedTube.videoTitle() ) { keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if(!keywords){keyword=''} ImprovedTube.speedException(); } - else { keywords = ''; (async function () { try { const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`); - - const htmlContent = await response.text(); - const metaRegex = /]+name=["'](keywords|genre|duration)["'][^>]+content=["']([^"']+)["'][^>]*>/gi; - let match; while ((match = metaRegex.exec(htmlContent)) !== null) { - const [, property, value] = match; - if (property === 'keywords') { keywords = value;} else {DATA[property] = value;} - } - amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false; - if (keywords) { ImprovedTube.speedException(); } - } catch (error) { console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; } - })(); - } - }; -if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { ImprovedTube.fetchDOMData();} -else { -//Invidious instances. Should be updated automatically!... -const invidiousInstances = ['invidious.fdn.fr','inv.tux.pizza','invidious.flokinet.to','invidious.protokolla.fi','invidious.private.coffee','yt.artemislena.eu','invidious.perennialte.ch','invidious.materialio.us','iv.datura.network']; -function getRandomInvidiousInstance() { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} - -(async function () { let retries = 4; let invidiousFetched = false; - async function fetchInvidiousData() { - try {const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); - DATA = await response.json(); + else { keywords = ''; (async function () { try { const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`); + + const htmlContent = await response.text(); + const metaRegex = /]+name=["'](keywords|genre|duration)["'][^>]+content=["']([^"']+)["'][^>]*>/gi; + let match; while ((match = metaRegex.exec(htmlContent)) !== null) { + const [, property, value] = match; + if (property === 'keywords') { keywords = value;} else {DATA[property] = value;} + } + amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false; + if (keywords) { ImprovedTube.speedException(); } + } catch (error) { console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; } + })(); + } + }; + if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { ImprovedTube.fetchDOMData();} + else { + //Invidious instances. Should be updated automatically!... + const invidiousInstances = ['invidious.fdn.fr','inv.tux.pizza','invidious.flokinet.to','invidious.protokolla.fi','invidious.private.coffee','yt.artemislena.eu','invidious.perennialte.ch','invidious.materialio.us','iv.datura.network']; + function getRandomInvidiousInstance() { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} + + (async function () { let retries = 4; let invidiousFetched = false; + async function fetchInvidiousData() { + try {const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); + DATA = await response.json(); if (DATA.genre && DATA.title && DATA.keywords && DATA.lengthSeconds) { if (DATA.keywords.toString() === defaultKeywords ) {DATA.keywords = ''} ImprovedTube.speedException(); invidiousFetched = true; } - } catch (error) { console.error('Error: Invidious API: ', error); } + } catch (error) { console.error('Error: Invidious API: ', error); } + } + while (retries > 0 && !invidiousFetched) { await fetchInvidiousData(); + if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; } } + if(!invidiousFetched){ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} + else { ImprovedTube.fetchDOMData();} } + })(); + } + } // else { } } - while (retries > 0 && !invidiousFetched) { await fetchInvidiousData(); - if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; } } - if(!invidiousFetched){ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} - else { ImprovedTube.fetchDOMData();} } -})(); } - } // else { } - } - } -} +} /*------------------------------------------------------------------------------ SUBTITLES ------------------------------------------------------------------------------*/ @@ -312,8 +312,8 @@ ImprovedTube.subtitlesUserSettings = function () { if (userSettings.length && player && player.getSubtitlesUserSettings && player.updateSubtitlesUserSettings) { let ytSettings = player.getSubtitlesUserSettings(), setting; - - if (!ytSettings) return; //null SubtitlesUserSettings seem to mean subtitles not available + + if (!ytSettings) return; //null SubtitlesUserSettings seem to mean subtitles not available for (const value of userSettings) { setting = null; @@ -336,7 +336,7 @@ ImprovedTube.subtitlesUserSettings = function () { setting = Number(ourSettings[value]) / 100; break; } - + if (ytSettings?.hasOwnProperty(value)) { ytSettings[value] = setting; } else { @@ -357,9 +357,9 @@ ImprovedTube.subtitlesDisableLyrics = function () { // Music detection only uses 3 identifiers for Lyrics: lyrics, sing-along, karaoke. // Easier to simply use those here. Can replace with music detection later. const terms = ["sing along", "sing-along", "karaoke", "lyric", "卡拉OK", "卡拉OK", "الكاريوكي", "караоке", "カラオケ","노래방"]; - if (terms.some(term => this.videoTitle().toLowerCase().includes(term))) { + if (terms.some(term => this.videoTitle().toLowerCase().includes(term))) { player.toggleSubtitles(); - } + } } } }; @@ -383,14 +383,14 @@ ImprovedTube.upNextAutoplay = function () { ADS ------------------------------------------------------------------------------*/ ImprovedTube.playerAds = function (parent) { - + let button = parent.querySelector('.ytp-ad-skip-button-modern.ytp-button,[class*="ytp-ad-skip-button"].ytp-button') || parent; // TODO: Replace this with centralized video element pointer let video = document.querySelector('.video-stream.html5-main-video') || false; function skipAd() { if (video) video.currentTime = video.duration; - if (button) button.click(); - } + if (button) button.click(); + } if (this.storage.ads === 'block_all') { skipAd(); } else if (this.storage.ads === 'subscribed_channels') { @@ -406,7 +406,7 @@ ImprovedTube.playerAds = function (parent) { let subscribersNumber = ImprovedTube.subscriberCount; if(subscribersNumber > userDefiniedLimit){ skipAd(); - } + } } }; /*------------------------------------------------------------------------------ @@ -480,16 +480,16 @@ ImprovedTube.playerQualityWithoutFocus = function () { BATTERY FEATURES; PLAYER QUALITY BASED ON POWER STATUS ------------------------------------------------------------------------------*/ ImprovedTube.batteryFeatures = async function () { - if (ImprovedTube.storage.qualityWhenRunningOnBattery - || ImprovedTube.storage.pauseWhileIUnplugTheCharger - || ImprovedTube.storage.whenBatteryIslowDecreaseQuality) { + if (ImprovedTube.storage.qualityWhenRunningOnBattery + || ImprovedTube.storage.pauseWhileIUnplugTheCharger + || ImprovedTube.storage.whenBatteryIslowDecreaseQuality) { const updateQuality = async (battery, charging) => { - if (battery) { - if (!battery.charging) { + if (battery) { + if (!battery.charging) { if (ImprovedTube.storage.pauseWhileIUnplugTheCharger && charging) { ImprovedTube.elements.player.pauseVideo(); ImprovedTube.paused = true; - } + } if (ImprovedTube.storage.qualityWhenRunningOnBattery) { ImprovedTube.playerQuality(ImprovedTube.storage.qualityWhenRunningOnBattery); } @@ -512,7 +512,7 @@ ImprovedTube.batteryFeatures = async function () { } } }; - const battery = await navigator.getBattery(); + const battery = await navigator.getBattery(); battery.addEventListener("levelchange", () => updateQuality(battery)); battery.addEventListener("chargingchange", () => updateQuality(battery, true)); await updateQuality(battery); @@ -619,11 +619,11 @@ ImprovedTube.screenshot = function () { 'image/png': blob }) ]) - .then(function () { console.log("ImprovedTube: Screeeeeeenshot tada!"); }) - .catch(function (error) { - console.log('ImprovedTube screenshot: ', error); - alert('ImprovedTube Screenshot to Clipboard error. Details in Debug Console.'); - }); + .then(function () { console.log("ImprovedTube: Screeeeeeenshot tada!"); }) + .catch(function (error) { + console.log('ImprovedTube screenshot: ', error); + alert('ImprovedTube Screenshot to Clipboard error. Details in Debug Console.'); + }); } else { let a = document.createElement('a'); a.href = URL.createObjectURL(blob); @@ -636,27 +636,27 @@ ImprovedTube.screenshot = function () { ImprovedTube.renderSubtitle = function (ctx,captionElements) { if (ctx && captionElements) { - captionElements.forEach(function (captionElement, index) { - var captionText = captionElement.textContent.trim(); - var captionStyles = window.getComputedStyle(captionElement); - - ctx.fillStyle = captionStyles.color; - ctx.font = captionStyles.font; - ctx.textAlign = 'center'; - ctx.textBaseline = 'bottom'; - var txtWidth = ctx.measureText(captionText).width; - var txtHeight = parseFloat(captionStyles.fontSize); - - var xOfset = (ctx.canvas.width - txtWidth) / 2; - - var padding = 5; // Adjust the padding as needed - var yofset = ctx.canvas.height - (captionElements.length - index) * (txtHeight + 2 * padding); - - ctx.fillStyle = captionStyles.backgroundColor; - ctx.fillRect(xOfset - padding, yofset - txtHeight - padding, txtWidth + 2 * padding, txtHeight + 2 * padding); - ctx.fillStyle = captionStyles.color; - ctx.fillText(captionText, xOfset + txtWidth / 2, yofset); - }); + captionElements.forEach(function (captionElement, index) { + var captionText = captionElement.textContent.trim(); + var captionStyles = window.getComputedStyle(captionElement); + + ctx.fillStyle = captionStyles.color; + ctx.font = captionStyles.font; + ctx.textAlign = 'center'; + ctx.textBaseline = 'bottom'; + var txtWidth = ctx.measureText(captionText).width; + var txtHeight = parseFloat(captionStyles.fontSize); + + var xOfset = (ctx.canvas.width - txtWidth) / 2; + + var padding = 5; // Adjust the padding as needed + var yofset = ctx.canvas.height - (captionElements.length - index) * (txtHeight + 2 * padding); + + ctx.fillStyle = captionStyles.backgroundColor; + ctx.fillRect(xOfset - padding, yofset - txtHeight - padding, txtWidth + 2 * padding, txtHeight + 2 * padding); + ctx.fillStyle = captionStyles.color; + ctx.fillText(captionText, xOfset + txtWidth / 2, yofset); + }); } }; @@ -677,19 +677,19 @@ ImprovedTube.playerScreenshotButton = function () { onclick: this.screenshot, title: 'Screenshot' }); - } + } }; /*------------------------------------------------------------------------------ REPEAT -------------------------------------------------------------------------------*/ -ImprovedTube.playerRepeat = function () { - setTimeout(function () { - if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { - ImprovedTube.elements.video.setAttribute('loop', ''); - } +ImprovedTube.playerRepeat = function () { + setTimeout(function () { + if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { + ImprovedTube.elements.video.setAttribute('loop', ''); + } //ImprovedTube.elements.buttons['it-repeat-styles'].style.opacity = '1'; //old class from version 3.x? that both repeat buttons could have }, 200); -} +} /*------------------------------------------------------------------------------ REPEAT BUTTON ------------------------------------------------------------------------------*/ @@ -700,21 +700,21 @@ ImprovedTube.playerRepeatButton = function () { svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z'); svg.appendChild(path); - var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } + var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } this.createPlayerButton({ id: 'it-repeat-button', child: svg, opacity: transparentOrOn, onclick: function () { var video = ImprovedTube.elements.video; - function matchLoopState(opacity) { - var thisButton = document.querySelector('#it-repeat-button'); - thisButton.style.opacity = opacity; - if (ImprovedTube.storage.below_player_loop !== false) { - var otherButton = document.querySelector('#it-below-player-loop'); - otherButton.children[0].style.opacity = opacity; - } - } if (video.hasAttribute('loop')) { + function matchLoopState(opacity) { + var thisButton = document.querySelector('#it-repeat-button'); + thisButton.style.opacity = opacity; + if (ImprovedTube.storage.below_player_loop !== false) { + var otherButton = document.querySelector('#it-below-player-loop'); + otherButton.children[0].style.opacity = opacity; + } + } if (video.hasAttribute('loop')) { video.removeAttribute('loop'); matchLoopState('.5') } else if (!/ad-showing/.test(ImprovedTube.elements.player.className)) { @@ -724,7 +724,7 @@ ImprovedTube.playerRepeatButton = function () { }, title: 'Repeat', }); - } + } }; /*------------------------------------------------------------------------------ ROTATE @@ -777,7 +777,7 @@ ImprovedTube.playerRotateButton = function () { }, title: 'Rotate' }); - } + } }; /*------------------------------------------------------------------------------ @@ -785,10 +785,10 @@ FIT-TO-WIN BUTTON ------------------------------------------------------------------------------*/ ImprovedTube.playerFitToWinButton = function () { if (this.storage.player_fit_to_win_button === true && (/watch\?/.test(location.href))) { - let tempContainer = document.createElement("div"); - tempContainer.innerHTML = ` + let tempContainer = document.createElement("div"); + tempContainer.innerHTML = ` `; - const svg = tempContainer.firstChild; + const svg = tempContainer.firstChild; this.createPlayerButton({ id: 'it-fit-to-win-player-button', child: svg, @@ -806,7 +806,7 @@ ImprovedTube.playerFitToWinButton = function () { }, title: 'Fit To Window' }); - } + } }; @@ -821,7 +821,7 @@ var xpath = function(xpathToExecute){ result.push( nodesSnapshot.snapshotItem(i) ); } return result; - } +} function createOverlay() { var overlay = document.createElement('div'); @@ -835,17 +835,17 @@ function createOverlay() { overlay.style.zIndex = '9999'; overlay.style.display = 'block'; document.body.appendChild(overlay); - } +} ImprovedTube.playerCinemaModeButton = function () { if (this.storage.player_cinema_mode_button && (/watch\?/.test(location.href))) { var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), - path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); // TODO: change path such that cinema mode has its own unique icon path.setAttributeNS(null, 'd', 'm 2.1852 2.2 h 3.7188 h 5.2974 h 5.184 h 3.5478 c 0.6012 0 1.1484 0.2737 1.5444 0.7113 c 0.396 0.4396 0.6408 1.047 0.6408 1.7143 v 1.4246 v 11.4386 v 1.4166 c 0 0.6673 -0.2466 1.2747 -0.6408 1.7143 c -0.396 0.4396 -0.9432 0.7113 -1.5444 0.7113 h -3.456 c -0.0288 0.006 -0.0594 0.008 -0.0918 0.008 c -0.0306 0 -0.0612 -0.002 -0.0918 -0.008 h -5.0004 c -0.0288 0.006 -0.0594 0.008 -0.0918 0.008 c -0.0306 0 -0.0612 -0.002 -0.0918 -0.008 h -5.1138 c -0.0288 0.006 -0.0594 0.008 -0.0918 0.008 c -0.0306 0 -0.0612 -0.002 -0.0918 -0.008 h -3.627 c -0.6012 0 -1.1484 -0.2737 -1.5444 -0.7113 s -0.6408 -1.047 -0.6408 -1.7143 v -1.4166 v -11.4386 v -1.4246 c 0 -0.6673 0.2466 -1.2747 0.6408 -1.7143 c 0.396 -0.4376 0.9432 -0.7113 1.5444 -0.7113 l 0 0 z m 7.749 6.2418 l 3.6954 2.8611 c 0.0576 0.04 0.1098 0.0959 0.1512 0.1618 c 0.1656 0.2657 0.1044 0.6274 -0.1332 0.8112 l -3.681 2.8252 c -0.09 0.0819 -0.207 0.1319 -0.333 0.1319 c -0.2916 0 -0.5274 -0.2617 -0.5274 -0.5854 v -5.7283 h 0.0018 c 0 -0.1159 0.0306 -0.2318 0.0936 -0.3337 c 0.1674 -0.2637 0.495 -0.3277 0.7326 -0.1439 l 0 0 z m 6.9768 9.6324 v 2.0879 h 3.0204 c 0.3114 0 0.594 -0.1419 0.7992 -0.3696 c 0.2052 -0.2278 0.333 -0.5415 0.333 -0.8871 v -0.8312 h -4.1526 l 0 0 z m -1.053 2.0879 v -2.0879 h -4.1292 v 2.0879 h 4.1292 l 0 0 z m -5.1822 0 v -2.0879 h -4.2444 v 2.0879 h 4.2444 l 0 0 z m -5.2992 0 v -2.0879 h -4.3236 v 0.8312 c 0 0.3457 0.1278 0.6593 0.333 0.8871 c 0.2052 0.2278 0.4878 0.3696 0.7992 0.3696 h 3.1914 l 0 0 z m -4.3236 -3.2567 h 4.851 h 5.2974 h 5.184 h 4.68 v -10.2697 h -4.68 h -5.184 h -5.2974 h -4.851 v 10.2697 l 0 0 z m 14.805 -11.4386 v -2.0979 h -4.1292 v 2.0959 h 4.1292 l 0 0.002 z m 1.053 -2.0979 v 2.0959 h 4.1526 v -0.8392 c 0 -0.3457 -0.1278 -0.6593 -0.333 -0.8871 c -0.2052 -0.2278 -0.4878 -0.3696 -0.7992 -0.3696 h -3.0204 l 0 0 z m -6.2352 2.0979 v -2.0979 h -4.2444 v 2.0959 h 4.2444 l 0 0.002 z m -5.2992 0 v -2.0979 h -3.1914 c -0.3114 0 -0.594 0.1419 -0.7992 0.3696 c -0.2052 0.2278 -0.333 0.5415 -0.333 0.8871 v 0.8392 h 4.3236 l 0 0.002 z'); - + svg.appendChild(path); this.createPlayerButton({ @@ -865,8 +865,8 @@ ImprovedTube.playerCinemaModeButton = function () { player.style.zIndex = 10000; svg.parentNode.style.opacity = 1; } - - + + var overlay = document.getElementById('overlay_cinema'); if (!overlay) { createOverlay(); @@ -877,7 +877,7 @@ ImprovedTube.playerCinemaModeButton = function () { }, title: 'Cinema Mode' }); - } + } } ImprovedTube.playerCinemaModeDisable = function () { @@ -895,26 +895,26 @@ ImprovedTube.playerCinemaModeDisable = function () { ImprovedTube.playerCinemaModeEnable = function () { if (this.storage.player_auto_cinema_mode || this.storage.player_auto_hide_cinema_mode_when_paused) { - - if ((/watch\?/.test(location.href))) { - var overlay = document.getElementById('overlay_cinema'); - - if (this.storage.player_auto_cinema_mode === true && !overlay) { - createOverlay(); - overlay = document.getElementById('overlay_cinema'); - } - -// console.log(overlay && this.storage.player_auto_hide_cinema_mode_when_paused === true || this.storage.player_auto_cinema_mode === true && overlay) - if (overlay) { - overlay.style.display = 'block' - var player = xpath('//*[@id="movie_player"]/div[1]/video')[0].parentNode.parentNode - player.style.zIndex = 10000; - // console.log(player) - var cinemaModeButton = xpath('//*[@id="it-cinema-mode-button"]')[0] - cinemaModeButton.style.opacity = 1 + + if ((/watch\?/.test(location.href))) { + var overlay = document.getElementById('overlay_cinema'); + + if (this.storage.player_auto_cinema_mode === true && !overlay) { + createOverlay(); + overlay = document.getElementById('overlay_cinema'); + } + + // console.log(overlay && this.storage.player_auto_hide_cinema_mode_when_paused === true || this.storage.player_auto_cinema_mode === true && overlay) + if (overlay) { + overlay.style.display = 'block' + var player = xpath('//*[@id="movie_player"]/div[1]/video')[0].parentNode.parentNode + player.style.zIndex = 10000; + // console.log(player) + var cinemaModeButton = xpath('//*[@id="it-cinema-mode-button"]')[0] + cinemaModeButton.style.opacity = 1 + } } } - } } /*------------------------------------------------------------------------------ @@ -934,41 +934,41 @@ ImprovedTube.playerHamburgerButton = function () { if(this.storage.player_hambur } let hamburgerMenu = document.querySelector('.custom-hamburger-menu'); - if (!hamburgerMenu) { - hamburgerMenu = document.createElement('div'); - hamburgerMenu.className = 'custom-hamburger-menu'; - hamburgerMenu.style.position = 'absolute'; - hamburgerMenu.style.right = '0'; - hamburgerMenu.style.marginTop = '8px'; - hamburgerMenu.style.cursor = 'pointer'; + if (!hamburgerMenu) { + hamburgerMenu = document.createElement('div'); + hamburgerMenu.className = 'custom-hamburger-menu'; + hamburgerMenu.style.position = 'absolute'; + hamburgerMenu.style.right = '0'; + hamburgerMenu.style.marginTop = '8px'; + hamburgerMenu.style.cursor = 'pointer'; + + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + svg.setAttribute('style', 'width: 32px; height: 32px;'); - const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - svg.setAttribute('style', 'width: 32px; height: 32px;'); + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z'); + path.setAttributeNS(null, 'fill', 'white'); - const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z'); - path.setAttributeNS(null, 'fill', 'white'); + svg.appendChild(path); + hamburgerMenu.appendChild(svg); - svg.appendChild(path); - hamburgerMenu.appendChild(svg); + controlsContainer.style.paddingRight = '40px'; + controlsContainer.parentNode.appendChild(hamburgerMenu); - controlsContainer.style.paddingRight = '40px'; - controlsContainer.parentNode.appendChild(hamburgerMenu); + let controlsVisible = true; + controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; + controlsVisible = false; - let controlsVisible = true; + hamburgerMenu.addEventListener('click', function () { controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; - controlsVisible = false; - - hamburgerMenu.addEventListener('click', function () { - controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; - controlsVisible = !controlsVisible; - - // Change the opacity of hamburgerMenu based on controls visibility - hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65'; - }); - } - } + controlsVisible = !controlsVisible; + + // Change the opacity of hamburgerMenu based on controls visibility + hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65'; + }); + } +} }; /*------------------------------------------------------------------------------ POPUP PLAYER @@ -1009,7 +1009,7 @@ ImprovedTube.playerPopupButton = function () { } //~ change focused tab to URL-less popup ImprovedTube.messages.send({ - action: 'fixPopup', + action: 'fixPopup', width: ytPlayer.offsetWidth * 0.75, height: ytPlayer.offsetHeight * 0.75, title: document.title @@ -1017,7 +1017,7 @@ ImprovedTube.playerPopupButton = function () { }, title: 'Popup' }); - } + } }; /*------------------------------------------------------------------------------ Force SDR @@ -1045,15 +1045,15 @@ ImprovedTube.playerControls = function () { player.onmouseenter = player.showControls; player.onmouseleave = player.hideControls; - player.onmousemove = (function() { + player.onmousemove = (function() { let thread, onmousestop = function() { - if (document.querySelector(".ytp-progress-bar:hover")) { - thread = setTimeout(onmousestop, 1000); - } else { - player.hideControls(); - } - }; + if (document.querySelector(".ytp-progress-bar:hover")) { + thread = setTimeout(onmousestop, 1000); + } else { + player.hideControls(); + } + }; return function() { player.showControls(); @@ -1072,9 +1072,9 @@ ImprovedTube.playerControls = function () { player.onmousemove = null; } }; -/*# HIDE VIDEO TITLE IN FULLSCREEN */ // Easier with CSS only (see player.css) +/*# HIDE VIDEO TITLE IN FULLSCREEN */ // Easier with CSS only (see player.css) //ImprovedTube.hideVideoTitleFullScreen = function (){ if (ImprovedTube.storage.hide_video_title_fullScreen === true) { -//document.addEventListener('fullscreenchange', function (){ document.querySelector(".ytp-title-text > a")?.style.setProperty('display', 'none'); }) }}; +//document.addEventListener('fullscreenchange', function (){ document.querySelector(".ytp-title-text > a")?.style.setProperty('display', 'none'); }) }}; /*------------------------------------------------------------------------------ CUSTOM MINI-PLAYER @@ -1427,7 +1427,7 @@ ImprovedTube.pauseWhileTypingOnYoutube = function () { if (ImprovedTube.storage. // Add event listener to the whole document document.addEventListener('keydown', function (e) { // Check on the storage for pause_while_typing_on_youtube_storage is false - + // If player is NOT in the viewport, return if (!isPlayerInViewport()) { return; diff --git a/js&css/web-accessible/www.youtube.com/playlist.js b/js&css/web-accessible/www.youtube.com/playlist.js index 0a38d37b0..8a09cf296 100644 --- a/js&css/web-accessible/www.youtube.com/playlist.js +++ b/js&css/web-accessible/www.youtube.com/playlist.js @@ -10,9 +10,9 @@ ImprovedTube.playlistUpNextAutoplay = function () { if (this.storage.playlist_up && playlistData.currentIndex && playlistData.totalVideos && playlistData.localCurrentIndex) { - playlistData.currentIndex = playlistData.totalVideos; - } + playlistData.currentIndex = playlistData.totalVideos; } +} }; /*------------------------------------------------------------------------------ 4.5.2 REVERSE @@ -84,7 +84,7 @@ ImprovedTube.playlistReverse = function () { } if (this.playlistReversed === true) { - update(); + update(); } } }; @@ -93,17 +93,17 @@ ImprovedTube.playlistReverse = function () { 4.5.3 REPEAT ------------------------------------------------------------------------------*/ ImprovedTube.playlistRepeat = function () { - if ( ImprovedTube.storage.playlist_repeat === true ) { + if ( ImprovedTube.storage.playlist_repeat === true ) { setTimeout(function (){ - var option = ImprovedTube.storage.playlist_repeat, - button = document.querySelector("#button.ytd-playlist-loop-button-renderer") || document.querySelector("ytd-playlist-loop-button-renderer button") || document.querySelector("ytd-playlist-loop-button-renderer"); - if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M21') - ) && button.querySelector("#tooltip")?.textContent !== 'Loop video' - && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Loop video' - && button.querySelector("#tooltip")?.textContent !== 'Turn off loop' - && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Turn off loop' - ) - { button.click(); } + var option = ImprovedTube.storage.playlist_repeat, + button = document.querySelector("#button.ytd-playlist-loop-button-renderer") || document.querySelector("ytd-playlist-loop-button-renderer button") || document.querySelector("ytd-playlist-loop-button-renderer"); + if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M21') + ) && button.querySelector("#tooltip")?.textContent !== 'Loop video' + && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Loop video' + && button.querySelector("#tooltip")?.textContent !== 'Turn off loop' + && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Turn off loop' + ) + { button.click(); } }, 10000); } }; @@ -114,14 +114,14 @@ ImprovedTube.playlistRepeat = function () { 4.5.4 SHUFFLE ------------------------------------------------------------------------------*/ ImprovedTube.playlistShuffle = function () { - if ( ImprovedTube.storage.playlist_shuffle === true ) { + if ( ImprovedTube.storage.playlist_shuffle === true ) { setTimeout(function (){ - var button = ImprovedTube.elements.playlist.shuffle_button, - option = ImprovedTube.storage.playlist_shuffle; - button = document.querySelector('#playlist-actions #playlist-action-menu ytd-toggle-button-renderer'); - if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M18.1') - ) ) - { button.click(); } + var button = ImprovedTube.elements.playlist.shuffle_button, + option = ImprovedTube.storage.playlist_shuffle; + button = document.querySelector('#playlist-actions #playlist-action-menu ytd-toggle-button-renderer'); + if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M18.1') + ) ) + { button.click(); } }, 10000); } }; @@ -154,13 +154,13 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c button.dataset.list = playlistID; button.style.opacity = '0.8'; button.addEventListener( - 'click', + 'click', (checkVideo ?? false) ? function () { const videoURL = ImprovedTube.elements.player?.getVideoUrl(); let width = ImprovedTube.elements.player.offsetWidth * 0.7 ?? innerWidth * 0.4; let height = ImprovedTube.elements.player.offsetHeight * 0.7 ?? innerHeight * 0.4; - "use strict"; + "use strict"; if (videoURL != null && ImprovedTube.regex.video_id.test(videoURL)) { ImprovedTube.elements.player.pauseVideo(); const listID = this.dataset.list, @@ -185,11 +185,11 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c } : function () { let width = ImprovedTube.elements.player.offsetWidth * 0.7 ?? innerWidth * 0.45; let height = ImprovedTube.elements.player.offsetHeight * 0.7 ?? innerHeight * 0.45; - if (!ImprovedTube.elements.player) { - shorts = /short/.test(this.parentElement.href); - if ( width / height < 1 ) { vertical = true } else { vertical = false } - if ( !vertical && shorts ){ width = height * 0.6} - if ( vertical && !shorts ){ height = width * 0.6} } + if (!ImprovedTube.elements.player) { + shorts = /short/.test(this.parentElement.href); + if ( width / height < 1 ) { vertical = true } else { vertical = false } + if ( !vertical && shorts ){ width = height * 0.6} + if ( vertical && !shorts ){ height = width * 0.6} } "use strict"; window.open(`${location.protocol}//www.youtube.com/embed/videoseries?autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}&list=${this.dataset.list}`, '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); //~ change focused tab to URL-less popup @@ -226,25 +226,25 @@ ImprovedTube.playlistPopupUpdate = function () { "use strict"; if (this.storage.playlist_popup === true){ - const playlistID = location.search.match(this.regex.playlist_id)?.[1], - playlistIDMini = this.elements.player?.getPlaylistId?.(); - - if (!document.contains(this.elements.buttons['it-popup-playlist-button-playlist'])) { - const playlistShareButton = document.body.querySelector('ytd-app>div#content>ytd-page-manager>ytd-browse>ytd-playlist-header-renderer ytd-button-renderer.ytd-playlist-header-renderer:has(button[title])'); - if (playlistShareButton == null) this.elements.buttons['it-popup-playlist-button-playlist'] = null; - else playlistShareButton.insertAdjacentElement('afterend', this.elements.buttons['it-popup-playlist-button-playlist'] = this.playlistPopupCreateButton(playlistID)); - } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-playlist'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-playlist'].dataset.list = playlistID; - - if (!document.contains(this.elements.buttons['it-popup-playlist-button-mini'])) { - const miniItemButtons = document.body.querySelector('ytd-app>ytd-miniplayer ytd-playlist-panel-renderer div#top-level-buttons-computed'); - if (miniItemButtons == null) this.elements.buttons['it-popup-playlist-button-mini'] = null; - else miniItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-mini'] = this.playlistPopupCreateButton(playlistIDMini, true, true)); - } else if (playlistIDMini != null && this.elements.buttons['it-popup-playlist-button-mini'].dataset.list !== playlistIDMini) this.elements.buttons['it-popup-playlist-button-mini'].dataset.list = playlistIDMini; -try { - if (!document.contains(this.elements.buttons['it-popup-playlist-button-panel'])) { - const panelItemButtons = document.body.querySelector('ytd-app>div#content>ytd-page-manager>ytd-watch-flexy ytd-playlist-panel-renderer div#top-level-buttons-computed'); - if (panelItemButtons == null) this.elements.buttons['it-popup-playlist-button-panel'] = null; - else panelItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-panel'] = this.playlistPopupCreateButton(playlistID, true, true)); - } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-panel'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-panel'].dataset.list = playlistID; -} catch (error) { console.error("Error appending playlist button panel:", error);} -}}; + const playlistID = location.search.match(this.regex.playlist_id)?.[1], + playlistIDMini = this.elements.player?.getPlaylistId?.(); + + if (!document.contains(this.elements.buttons['it-popup-playlist-button-playlist'])) { + const playlistShareButton = document.body.querySelector('ytd-app>div#content>ytd-page-manager>ytd-browse>ytd-playlist-header-renderer ytd-button-renderer.ytd-playlist-header-renderer:has(button[title])'); + if (playlistShareButton == null) this.elements.buttons['it-popup-playlist-button-playlist'] = null; + else playlistShareButton.insertAdjacentElement('afterend', this.elements.buttons['it-popup-playlist-button-playlist'] = this.playlistPopupCreateButton(playlistID)); + } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-playlist'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-playlist'].dataset.list = playlistID; + + if (!document.contains(this.elements.buttons['it-popup-playlist-button-mini'])) { + const miniItemButtons = document.body.querySelector('ytd-app>ytd-miniplayer ytd-playlist-panel-renderer div#top-level-buttons-computed'); + if (miniItemButtons == null) this.elements.buttons['it-popup-playlist-button-mini'] = null; + else miniItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-mini'] = this.playlistPopupCreateButton(playlistIDMini, true, true)); + } else if (playlistIDMini != null && this.elements.buttons['it-popup-playlist-button-mini'].dataset.list !== playlistIDMini) this.elements.buttons['it-popup-playlist-button-mini'].dataset.list = playlistIDMini; + try { + if (!document.contains(this.elements.buttons['it-popup-playlist-button-panel'])) { + const panelItemButtons = document.body.querySelector('ytd-app>div#content>ytd-page-manager>ytd-watch-flexy ytd-playlist-panel-renderer div#top-level-buttons-computed'); + if (panelItemButtons == null) this.elements.buttons['it-popup-playlist-button-panel'] = null; + else panelItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-panel'] = this.playlistPopupCreateButton(playlistID, true, true)); + } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-panel'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-panel'].dataset.list = playlistID; + } catch (error) { console.error("Error appending playlist button panel:", error);} + }}; diff --git a/js&css/web-accessible/www.youtube.com/shortcuts.js b/js&css/web-accessible/www.youtube.com/shortcuts.js index a113fd23f..de0c26fe0 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -113,16 +113,16 @@ ImprovedTube.shortcuts = function () { case 'shift': case 'toggle': potentialShortcut[button] = keys[button] || false; - break + break case 'wheel': potentialShortcut[button] = keys[button] || 0; - break + break case 'keys': // array of sorted scancodes potentialShortcut[button] = keys[button] ? Object.keys(keys[button]).map(s=>Number(s)).sort() : []; - break + break } } if (potentialShortcut['keys'] || potentialShortcut['wheel']) this.input.listening[camelName] = potentialShortcut; @@ -420,16 +420,16 @@ ImprovedTube.shortcutActivateCaptions = function () { } }; /*------Chapters------*/ -ImprovedTube.shortcutChapters = function () { - try{var height = document.querySelector('*[target-id*=chapters]').clientHeight;}catch{} - if (height) {try{document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close")} catch{}} - else { try{document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open")} catch{} } -}; +ImprovedTube.shortcutChapters = function () { + try{var height = document.querySelector('*[target-id*=chapters]').clientHeight;}catch{} + if (height) {try{document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close")} catch{}} + else { try{document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open")} catch{} } +}; /*------Transcript------*/ -ImprovedTube.shortcutTranscript = function () { - try{var height = document.querySelector('*[target-id*=transcript]').clientHeight;}catch{} - if (height) {try{document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close")} catch{}} - else { try{document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open")} catch{} } +ImprovedTube.shortcutTranscript = function () { + try{var height = document.querySelector('*[target-id*=transcript]').clientHeight;}catch{} + if (height) {try{document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close")} catch{}} + else { try{document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open")} catch{} } }; /*------------------------------------------------------------------------------ 4.7.22 LIKE @@ -445,19 +445,19 @@ ImprovedTube.shortcutDislike = function () { }; /*------Report------*/ ImprovedTube.shortcutReport = function () { -try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); - document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} + try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); + document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} catch{console.log("'...' failed"); setTimeout(function(){try{document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} -catch{console.log("'...' failed2")}},100) } - -setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} + catch{console.log("'...' failed2")}},100) } + + setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} catch{console.log("report failed");setTimeout(function() {try{document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} - catch{console.log("report failed2");document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}},800); - } -},200); + catch{console.log("report failed2");document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}},800); + } + },200); -setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed"); - setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed2");}},1700)}},700) + setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed"); + setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed2");}},1700)}},700) } /*------------------------------------------------------------------------------ 4.7.24 SUBSCRIBE @@ -514,7 +514,7 @@ ImprovedTube.shortcutStatsForNerds = function () { console.error('shortcutStatsForNerds: Need valid Player element'); return; } - + if (player.isVideoInfoVisible()) { player.hideVideoInfo(); } else { diff --git a/js&css/web-accessible/www.youtube.com/themes.js b/js&css/web-accessible/www.youtube.com/themes.js index 023e5fa09..c63d6464c 100644 --- a/js&css/web-accessible/www.youtube.com/themes.js +++ b/js&css/web-accessible/www.youtube.com/themes.js @@ -3,26 +3,26 @@ ------------------------------------------------------------------------------*/ ImprovedTube.myColors = function () { if (this.storage.theme === 'custom') { - var style = this.elements.my_colors || document.createElement('style'), - primary_color = this.storage.theme_primary_color, - text_color = this.storage.theme_text_color; + var style = this.elements.my_colors || document.createElement('style'), + primary_color = this.storage.theme_primary_color, + text_color = this.storage.theme_text_color; - if (primary_color) { - primary_color = 'rgb(' + primary_color.join(',') + ')'; - } else { - // need better central place for storing default custom profile colors - primary_color = 'rgb(200, 200, 200)'; - } + if (primary_color) { + primary_color = 'rgb(' + primary_color.join(',') + ')'; + } else { + // need better central place for storing default custom profile colors + primary_color = 'rgb(200, 200, 200)'; + } - if (text_color) { - text_color = 'rgb(' + text_color.join(',') + ')'; - } else { - // need better central place for storing default custom profile colors - text_color = 'rgb(25, 25, 25)'; - } + if (text_color) { + text_color = 'rgb(' + text_color.join(',') + ')'; + } else { + // need better central place for storing default custom profile colors + text_color = 'rgb(25, 25, 25)'; + } - style.className = 'it-theme-editor'; - style.textContent = 'html, [dark] {' + + style.className = 'it-theme-editor'; + style.textContent = 'html, [dark] {' + '--yt-swatch-textbox-bg:rgba(19,19,19,1)!important;' + '--yt-swatch-icon-color:rgba(136,136,136,1)!important;' + '--yt-spec-brand-background-primary:rgba(0,0,0, 0.1) !important;' + @@ -70,14 +70,14 @@ ImprovedTube.myColors = function () { 'background-color: var(--yt-spec-base-background)!important;' + '}'; - this.elements.my_colors = style; - document.documentElement.appendChild(style); - document.documentElement.removeAttribute('dark'); - document.querySelector('ytd-masthead')?.removeAttribute('dark'); - document.getElementById('cinematics')?.style.setProperty("display", "none"); - } else { - this.elements.my_colors?.remove(); - } + this.elements.my_colors = style; + document.documentElement.appendChild(style); + document.documentElement.removeAttribute('dark'); + document.querySelector('ytd-masthead')?.removeAttribute('dark'); + document.getElementById('cinematics')?.style.setProperty("display", "none"); + } else { + this.elements.my_colors?.remove(); + } } ImprovedTube.setTheme = function () { diff --git a/menu/index.js b/menu/index.js index 4873dd1f0..00617bcfb 100644 --- a/menu/index.js +++ b/menu/index.js @@ -2,12 +2,12 @@ >>> INDEX: /*-------------------------------------------------------------- ---------------------------------------------------------------- -# Global variable //moved to skeleton.js: (var extension = {skeleton:{} }; +# Global variable //moved to skeleton.js: (var extension = {skeleton:{} }; # INITIALIZATION --------------------------------------------------------------*/ satus.storage.import(function (items) { var language = items.language; - if (!language || language === 'default') { language = false;} + if (!language || language === 'default') { language = false;} satus.locale.import(language, function () { satus.render(extension.skeleton); diff --git a/menu/satus.js b/menu/satus.js index 3e229bd70..3bd5917be 100644 --- a/menu/satus.js +++ b/menu/satus.js @@ -250,7 +250,7 @@ satus.isNumber = function(t) { return (typeof t ==='number' && !isNaN(t)); }; satus.isObject = function(t) { return (t instanceof Object && t !== null); }; satus.isElement = function(t) { return (t instanceof Element || t instanceof HTMLDocument); }; satus.isNodeList = function(t) { return t instanceof NodeList; }; -satus.isBoolean = function(t) { return (t === false || t === true); }; +satus.isBoolean = function(t) { return (t === false || t === true); }; /*---LOG------------------------------------------------------*/ satus.log =function(){console.log.apply(null, arguments);}; @@ -760,21 +760,21 @@ satus.render = function(skeleton, container, property, childrenOnly, prepend, sk var parent = element, key = skeleton.storage || property || false, value; - + if (satus.isFunction(key)) { key = key(); } - + if (skeleton.storage !== false) { if (key) { value = satus.storage.get(key); } - + if (skeleton.hasOwnProperty('value') && value === undefined) { value = skeleton.value; } } - + return Object.defineProperties({}, { key: { get: function() { @@ -790,10 +790,10 @@ satus.render = function(skeleton, container, property, childrenOnly, prepend, sk }, set: function(val) { value = val; - + if (satus.storage.get(key) != val) { satus.storage.set(key, val); - + parent.dispatchEvent(new CustomEvent('change')); } } @@ -1055,12 +1055,12 @@ satus.locale.import = function(code, callback, path) { fetch(url) .then(response => response.ok ? response.json() : {}) .then(data => { - for (var key in data) { - if (!satus.locale.data[key]) { - satus.locale.data[key] = data[key].message; + for (var key in data) { + if (!satus.locale.data[key]) { + satus.locale.data[key] = data[key].message; + } } - } - }) + }) .catch(() => {}) .finally(() => successCallback && successCallback()); } @@ -1161,7 +1161,7 @@ satus.components.modal = function(component, skeleton) { case 'vertical-menu': this.parentNode.close(); break; - + case 'shortcut': case 'color-picker': // click cancel button @@ -1469,7 +1469,7 @@ satus.components.textField = function(component, skeleton) { component.pre.update(); component.cursor.update(); }; - + document.addEventListener('selectionchange', selectionchange); input.addEventListener('input', function() { @@ -2928,7 +2928,7 @@ satus.user.os.bitness = function() { satus.user.browser.name = function() { var user_agent = navigator.userAgent; - if (!!navigator.brave) { + if (navigator.brave) { return 'Brave'; } else if (user_agent.indexOf("Opera") != -1 || user_agent.indexOf('OPR') != -1) { return 'Opera'; @@ -2938,8 +2938,8 @@ satus.user.browser.name = function() { return 'Edge'; } else if (user_agent.indexOf('Chrome') !== -1) { return 'Chrome'; - } else if (user_agent.indexOf('Safari') !== -1 - && (!/Windows|Chrom/.test(user_agent) + } else if (user_agent.indexOf('Safari') !== -1 + && (!/Windows|Chrom/.test(user_agent) || /Macintosh|iPhone/.test(user_agent))) { return 'Safari'; } else if (user_agent.indexOf('Firefox') !== -1) { diff --git a/menu/skeleton-parts/appearance.js b/menu/skeleton-parts/appearance.js index 5569abafe..066a45efe 100644 --- a/menu/skeleton-parts/appearance.js +++ b/menu/skeleton-parts/appearance.js @@ -8,11 +8,11 @@ # Footer # Sidebar --------------------------------------------------------------*/ -satus.storage.onchanged((key, value) => { - if (key === "related_videos" && value === "Titles") { - satus.storage.set('relatedVideosPrev', "Titles"); - console.log(satus.storage.get("relatedVideosPrev")); - } +satus.storage.onchanged((key, value) => { + if (key === "related_videos" && value === "Titles") { + satus.storage.set('relatedVideosPrev', "Titles"); + console.log(satus.storage.get("relatedVideosPrev")); + } }); extension.skeleton.main.layers.section.appearance = { component: "button", @@ -154,7 +154,7 @@ extension.skeleton.main.layers.section.appearance.on.click.player = { }, { text: "Max. width within the page", value: "max_width" - }, { + }, { text: "fitToWindow", value: "fit_to_window" }, { @@ -402,7 +402,7 @@ extension.skeleton.main.layers.section.appearance.on.click.player = { component: "switch", text: "hideScrollForDetails", tags: "remove,hide" - } + } } } }; @@ -443,7 +443,7 @@ extension.skeleton.main.layers.section.appearance.on.click.details = { component: 'section', variant: 'card', title: 'Currently_requiring_a_YouTube_API_key', - + how_long_ago_the_video_was_uploaded: { component: "switch", text: "howLongAgoTheVideoWasUploaded" @@ -460,19 +460,19 @@ extension.skeleton.main.layers.section.appearance.on.click.description = { component: "select", variant: "description", text: "description", - options: [{ - text: "normal", - value: "normal" - }, { - text: "expanded", - value: "expanded" - }, { - text: "sidebar", - value: "sidebar" - }, { - text: "hidden", - value: "hidden" - }/*, { + options: [{ + text: "normal", + value: "normal" + }, { + text: "expanded", + value: "expanded" + }, { + text: "sidebar", + value: "sidebar" + }, { + text: "hidden", + value: "hidden" + }/*, { text: "Classic", value: "classic" }, { @@ -483,240 +483,240 @@ extension.skeleton.main.layers.section.appearance.on.click.description = { value: "classic_hidden" }*/], tags: "hide,remove" -}; +}; extension.skeleton.main.layers.section.appearance.on.click.hide_detail_button = { component: "button", text: "Buttons", variant: "detailButton", on: { - click: { - component: 'section', - variant: 'card', - extraButtons: { - component: 'section', - variant: 'card', - title: 'ExtraButtons', + click: { + component: 'section', + variant: 'card', + extraButtons: { + component: 'section', + variant: 'card', + title: 'ExtraButtons', - below_player_screenshot: { - component: 'switch', - text: 'screenshot', - value: true - }, - below_player_pip: { - component: 'switch', - text: 'pictureInPicture', - value: true - }, - below_player_loop: { - component: 'switch', - text: 'loop', - value: true - } - }, - youtubeDetailButtons: { - component: "select", - text: "youTubeButtons", - options: [{ - text: "normal", - value: "normal" - }, { - text: 'removeNames', - value: "remove_labels" - }, { - text: 'halfTransparent', - value: "half_transparent" - }, { - text: 'Remove', - value: "remove" - }, { - text: 'TransparentBackground', - value: "transparent_background" - }, { - text: "hide_labels", - value: "hide_labels" - }, { - text: 'removeIcons', - value: "remove_icons" - }], - tags: "hide,remove" - }, - detailButtons: { - component: 'section', - variant: 'card', - purchase: { - component: "select", - text: "purchase", - options: [{ - text: "normal", - value: "normal" - }, { - text: "removeName", - value: "remove_label" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove,purchase-button" - }, - join: { - component: "select", - text: "join", - options: [{ - text: "normal", - value: "normal" - }, { - text: "removeName", - value: "remove_label" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove,join-button" - }, - subscribe: { - component: "select", - text: "subscribe", - options: [{ - text: "normal", - value: "normal" - }, { - text: "removeName", - value: "remove_label" - }, { - text: "grey", - value: "grey" - }, { - text: "transparentColor", - value: "transparent" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove,subscribe-button" - }, - likes: { - component: "select", - text: "like", - options: [{ - text: "normal", - value: "normal" - }, { - text: "iconsOnly", - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_dislike_button: { - component: "select", - text: "dislike", - options: [{ - text: 'normal', - value: "normal" - }, { - text: 'iconsOnly', - value: "icons_only" - }, { - text: 'hidden', - value: "hidden" - }], - tags: "hide,remove" - }, - red_dislike_button: { - component: 'switch', - text: "redDislikeButton" - }, - hide_share_button: { - component: "select", - text: "share", - options: [{ - text: "normal", - value: "normal" - }, { - text: "iconsOnly", - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_download_button: { - component: "select", - text: 'Download', - options: [{ - text: "normal", - value: "normal" - }, { - text: "iconsOnly", - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_thanks_button: { - component: "select", - text: 'thanks', - options: [{ - text: 'normal', - value: "normal" - }, { - text: 'iconsOnly', - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_clip_button: { - component: "select", - text: 'clip', - options: [{ - text: 'normal', - value: "normal" - }, { - text: 'iconsOnly', - value: "icons_only" - }, { - text: "hidden", - value: "hidden" - }], - tags: "hide,remove" - }, - hide_save_button: { - component: "select", - text: 'save', - options: [{ - text: 'normal', - value: "normal" - }, { - text: 'iconsOnly', - value: "icons_only" - }, { - text: 'hidden', - value: "hidden" - }], - tags: "hide,remove" - }, - hide_report_button: { - component: "switch", - text: 'hideReport', - tags: "hide,remove" - }, - hide_more_button: { - component: "switch", - text: 'hideMore', - tags: "hide,remove" - } - } - } + below_player_screenshot: { + component: 'switch', + text: 'screenshot', + value: true + }, + below_player_pip: { + component: 'switch', + text: 'pictureInPicture', + value: true + }, + below_player_loop: { + component: 'switch', + text: 'loop', + value: true + } + }, + youtubeDetailButtons: { + component: "select", + text: "youTubeButtons", + options: [{ + text: "normal", + value: "normal" + }, { + text: 'removeNames', + value: "remove_labels" + }, { + text: 'halfTransparent', + value: "half_transparent" + }, { + text: 'Remove', + value: "remove" + }, { + text: 'TransparentBackground', + value: "transparent_background" + }, { + text: "hide_labels", + value: "hide_labels" + }, { + text: 'removeIcons', + value: "remove_icons" + }], + tags: "hide,remove" + }, + detailButtons: { + component: 'section', + variant: 'card', + purchase: { + component: "select", + text: "purchase", + options: [{ + text: "normal", + value: "normal" + }, { + text: "removeName", + value: "remove_label" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove,purchase-button" + }, + join: { + component: "select", + text: "join", + options: [{ + text: "normal", + value: "normal" + }, { + text: "removeName", + value: "remove_label" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove,join-button" + }, + subscribe: { + component: "select", + text: "subscribe", + options: [{ + text: "normal", + value: "normal" + }, { + text: "removeName", + value: "remove_label" + }, { + text: "grey", + value: "grey" + }, { + text: "transparentColor", + value: "transparent" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove,subscribe-button" + }, + likes: { + component: "select", + text: "like", + options: [{ + text: "normal", + value: "normal" + }, { + text: "iconsOnly", + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_dislike_button: { + component: "select", + text: "dislike", + options: [{ + text: 'normal', + value: "normal" + }, { + text: 'iconsOnly', + value: "icons_only" + }, { + text: 'hidden', + value: "hidden" + }], + tags: "hide,remove" + }, + red_dislike_button: { + component: 'switch', + text: "redDislikeButton" + }, + hide_share_button: { + component: "select", + text: "share", + options: [{ + text: "normal", + value: "normal" + }, { + text: "iconsOnly", + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_download_button: { + component: "select", + text: 'Download', + options: [{ + text: "normal", + value: "normal" + }, { + text: "iconsOnly", + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_thanks_button: { + component: "select", + text: 'thanks', + options: [{ + text: 'normal', + value: "normal" + }, { + text: 'iconsOnly', + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_clip_button: { + component: "select", + text: 'clip', + options: [{ + text: 'normal', + value: "normal" + }, { + text: 'iconsOnly', + value: "icons_only" + }, { + text: "hidden", + value: "hidden" + }], + tags: "hide,remove" + }, + hide_save_button: { + component: "select", + text: 'save', + options: [{ + text: 'normal', + value: "normal" + }, { + text: 'iconsOnly', + value: "icons_only" + }, { + text: 'hidden', + value: "hidden" + }], + tags: "hide,remove" + }, + hide_report_button: { + component: "switch", + text: 'hideReport', + tags: "hide,remove" + }, + hide_more_button: { + component: "switch", + text: 'hideMore', + tags: "hide,remove" + } + } } + } } @@ -766,7 +766,7 @@ extension.skeleton.main.layers.section.appearance.on.click.comments = { columns: { component: "switch", text: "columns", - value: true + value: true }, squared_user_images: { component: 'switch', @@ -787,7 +787,7 @@ extension.skeleton.main.layers.section.appearance.on.click.comments = { }; /*-------------------------------------------------------------- -# POPUP AD +# POPUP AD --------------------------------------------------------------*/ extension.skeleton.main.layers.section.appearance.on.click.popup_ad = { @@ -839,15 +839,15 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { tags: "right", on: { click: function () { - setTimeout(() => { - if (satus.storage.get('related_videos')==="Titles" + setTimeout(() => { + if (satus.storage.get('related_videos')==="Titles" && satus.storage.get("relatedVideosPrev") ==="Titles") {if (!satus.storage.get('thumbnails_right')) { this.nextSibling.nextSibling.click(); satus.storage.set('relatedVideosPrev', "notTitles") - } - } - }, 650) - + } + } + }, 650) + } } }, @@ -869,7 +869,7 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { value: false, id: 'transcript', on: { - click: function () { setTimeout(() => { + click: function () { setTimeout(() => { if (satus.storage.get('transcript')) { if (satus.storage.get('no_page_margin')) { this.nextSibling.nextSibling.click(); @@ -886,10 +886,10 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { no_page_margin: { component: 'switch', text: 'To_the_side_No_page_margin', - + value: false, on: { - click: function () { setTimeout(() => { + click: function () { setTimeout(() => { if (satus.storage.get('no_page_margin')) { if (satus.storage.get('transcript')) { this.previousSibling.previousSibling.click(); @@ -905,7 +905,7 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { hide_shorts_remixing: { component: "switch", text: 'Hide_Shorts_remixing_this_video' - }, + }, livechat: { component: "select", text: 'liveChat', diff --git a/menu/skeleton-parts/blocklist.js b/menu/skeleton-parts/blocklist.js index d18a7f9be..259404c5b 100644 --- a/menu/skeleton-parts/blocklist.js +++ b/menu/skeleton-parts/blocklist.js @@ -107,10 +107,10 @@ extension.skeleton.main.layers.section.blocklist = { let blocklist = satus.storage.get('blocklist'); if (blocklist && blocklist.channels && Object.keys(blocklist.channels).length) { - this.textContent = '('+Object.keys(blocklist.channels).length+')'; - } else { - this.textContent = '(empty)'; - } + this.textContent = '('+Object.keys(blocklist.channels).length+')'; + } else { + this.textContent = '(empty)'; + } } } } @@ -205,10 +205,10 @@ extension.skeleton.main.layers.section.blocklist = { let blocklist = satus.storage.get('blocklist'); if (blocklist && blocklist.videos && Object.keys(blocklist.videos).length) { - this.textContent = '('+Object.keys(blocklist.videos).length+')'; - } else { - this.textContent = '(empty)'; - } + this.textContent = '('+Object.keys(blocklist.videos).length+')'; + } else { + this.textContent = '(empty)'; + } } } } diff --git a/menu/skeleton-parts/dark-light-switch.js b/menu/skeleton-parts/dark-light-switch.js index 0c44d9fb0..f8f276d05 100644 --- a/menu/skeleton-parts/dark-light-switch.js +++ b/menu/skeleton-parts/dark-light-switch.js @@ -1,57 +1,57 @@ const isDark = () => { - const themeElement = satus.storage.get('theme') - const lightThemes = ['desert', 'dawn', 'plain', 'default'] - const darkThemes = ['sunset', 'night', 'dark', 'black'] - return darkThemes.includes(themeElement) + const themeElement = satus.storage.get('theme') + const lightThemes = ['desert', 'dawn', 'plain', 'default'] + const darkThemes = ['sunset', 'night', 'dark', 'black'] + return darkThemes.includes(themeElement) } extension.skeleton.header.sectionEnd.darkLightSwitch.svgSun.on = { - render: function () { - console.log(satus.storage.get('lastLightTheme') + " " + satus.storage.get('lastDarkTheme')) - if(isDark()) { - this.style.display = 'none' - } - } + render: function () { + console.log(satus.storage.get('lastLightTheme') + " " + satus.storage.get('lastDarkTheme')) + if(isDark()) { + this.style.display = 'none' + } + } } extension.skeleton.header.sectionEnd.darkLightSwitch.svgMoon.on = { - render: function () { - if(!isDark()) { - this.style.display = 'none' - } - } + render: function () { + if(!isDark()) { + this.style.display = 'none' + } + } } extension.skeleton.header.sectionEnd.darkLightSwitch.on = { - click: function () { - if(isDark()) { - if (satus.storage.get('lastLightTheme')) { - satus.storage.set('theme', satus.storage.get("lastLightTheme")) - } else { - satus.storage.set('theme', 'default') - } - document.getElementById('dark-light-switch-icon-sun').style.display = '' - document.getElementById('dark-light-switch-icon-moon').style.display = 'none' - } else { - if (satus.storage.get('lastDarkTheme')) { - satus.storage.set('theme', satus.storage.get("lastDarkTheme")) - } else { - satus.storage.set('theme', 'black') - } - document.getElementById('dark-light-switch-icon-sun').style.display = 'none' - document.getElementById('dark-light-switch-icon-moon').style.display = '' - } - } + click: function () { + if(isDark()) { + if (satus.storage.get('lastLightTheme')) { + satus.storage.set('theme', satus.storage.get("lastLightTheme")) + } else { + satus.storage.set('theme', 'default') + } + document.getElementById('dark-light-switch-icon-sun').style.display = '' + document.getElementById('dark-light-switch-icon-moon').style.display = 'none' + } else { + if (satus.storage.get('lastDarkTheme')) { + satus.storage.set('theme', satus.storage.get("lastDarkTheme")) + } else { + satus.storage.set('theme', 'black') + } + document.getElementById('dark-light-switch-icon-sun').style.display = 'none' + document.getElementById('dark-light-switch-icon-moon').style.display = '' + } + } } satus.storage.onchanged(() => { - if(isDark()) { - document.getElementById('dark-light-switch-icon-sun').style.display = 'none' - document.getElementById('dark-light-switch-icon-moon').style.display = '' - satus.storage.set('lastDarkTheme', satus.storage.get('theme')) - } else { - document.getElementById('dark-light-switch-icon-sun').style.display = '' - document.getElementById('dark-light-switch-icon-moon').style.display = 'none' - satus.storage.set('lastLightTheme', satus.storage.get('theme')) - } -}) + if(isDark()) { + document.getElementById('dark-light-switch-icon-sun').style.display = 'none' + document.getElementById('dark-light-switch-icon-moon').style.display = '' + satus.storage.set('lastDarkTheme', satus.storage.get('theme')) + } else { + document.getElementById('dark-light-switch-icon-sun').style.display = '' + document.getElementById('dark-light-switch-icon-moon').style.display = 'none' + satus.storage.set('lastLightTheme', satus.storage.get('theme')) + } +}) diff --git a/menu/skeleton-parts/general.js b/menu/skeleton-parts/general.js index 06e393fb0..2d41a550a 100644 --- a/menu/skeleton-parts/general.js +++ b/menu/skeleton-parts/general.js @@ -34,7 +34,7 @@ extension.skeleton.main.layers.section.general = { value: 'below_player' }] }, - /* improvedTubeSidePanel: { + /* improvedTubeSidePanel: { component: 'switch', text: 'improvedTubeSidePanel' }, @@ -42,11 +42,11 @@ extension.skeleton.main.layers.section.general = { component: 'select', text: 'defaultContentCountry', options:[{text:"default",value:"default"},{text:"Afghanistan",value:"AF"},{text:"Albania",value:"AL"},{text:"Algeria",value:"DZ"},{text:"AmericanSamoa",value:"AS"},{text:"Andorra",value:"AD"},{text:"Angola",value:"AO"},{text:"Anguilla",value:"AI"},{text:"Antarctica",value:"AQ"},{text:"AntiguaandBarbuda",value:"AG"},{text:"Argentina",value:"AR"},{text:"Armenia",value:"AM"},{text:"Aruba",value:"AW"},{text:"Australia",value:"AU"},{text:"Austria",value:"AT"},{text:"Azerbaijan",value:"AZ"},{text:"Bahrain",value:"BH"},{text:"BailiwickofGuernsey",value:"GG"},{text:"Bangladesh",value:"BD"},{text:"Barbados",value:"BB"},{text:"Belarus",value:"BY"},{text:"Belgium",value:"BE"},{text:"Belize",value:"BZ"},{text:"Benin",value:"BJ"},{text:"Bermuda",value:"BM"},{text:"Bhutan",value:"BT"},{text:"Bolivia",value:"BO"},{text:"Bonaire",value:"BQ"},{text:"BosniaandHerzegovina",value:"BA"},{text:"Botswana",value:"BW"},{text:"BouvetIsland",value:"BV"},{text:"Brazil",value:"BR"},{text:"BritishIndianOceanTerritory",value:"IO"},{text:"BritishVirginIslands",value:"VG"},{text:"Brunei",value:"BN"},{text:"Bulgaria",value:"BG"},{text:"BurkinaFaso",value:"BF"},{text:"Burundi",value:"BI"},{text:"Cambodia",value:"KH"},{text:"Cameroon",value:"CM"},{text:"Canada",value:"CA"},{text:"CapeVerde",value:"CV"},{text:"CaymanIslands",value:"KY"},{text:"CentralAfricanRepublic",value:"CF"},{text:"Chad",value:"TD"},{text:"Chile",value:"CL"},{text:"China",value:"CN"},{text:"ChristmasIsland",value:"CX"},{text:"Cocos(Keeling)Islands",value:"CC"},{text:"CollectivityofSaintMartin",value:"MF"},{text:"Colombia",value:"CO"},{text:"Comoros",value:"KM"},{text:"CookIslands",value:"CK"},{text:"CostaRica",value:"CR"},{text:"Croatia",value:"HR"},{text:"Cuba",value:"CU"},{text:"Curaçao",value:"CW"},{text:"Cyprus",value:"CY"},{text:"CzechRepublic",value:"CZ"},{text:"DemocraticRepublicoftheCongo",value:"CD"},{text:"Denmark",value:"DK"},{text:"Djibouti",value:"DJ"},{text:"Dominica",value:"DM"},{text:"DominicanRepublic",value:"DO"},{text:"EastTimor",value:"TL"},{text:"Ecuador",value:"EC"},{text:"Egypt",value:"EG"},{text:"ElSalvador",value:"SV"},{text:"EquatorialGuinea",value:"GQ"},{text:"Eritrea",value:"ER"},{text:"Estonia",value:"EE"},{text:"Eswatini",value:"SZ"},{text:"Ethiopia",value:"ET"},{text:"FalklandIslands",value:"FK"},{text:"FaroeIslands",value:"FO"},{text:"FederatedStatesofMicronesia",value:"FM"},{text:"Fiji",value:"FJ"},{text:"Finland",value:"FI"},{text:"France",value:"FR"},{text:"FrenchGuiana",value:"GF"},{text:"FrenchPolynesia",value:"PF"},{text:"FrenchSouthernandAntarcticLands",value:"TF"},{text:"Gabon",value:"GA"},{text:"Georgia(country)",value:"GE"},{text:"Germany",value:"DE"},{text:"Ghana",value:"GH"},{text:"Gibraltar",value:"GI"},{text:"Greece",value:"GR"},{text:"Greenland",value:"GL"},{text:"Grenada",value:"GD"},{text:"Guadeloupe",value:"GP"},{text:"Guam",value:"GU"},{text:"Guatemala",value:"GT"},{text:"Guinea",value:"GN"},{text:"Guinea-Bissau",value:"GW"},{text:"Guyana",value:"GY"},{text:"Haiti",value:"HT"},{text:"HeardIslandandMcDonaldIslands",value:"HM"},{text:"HolySee",value:"VA"},{text:"Honduras",value:"HN"},{text:"HongKong",value:"HK"},{text:"Hungary",value:"HU"},{text:"Iceland",value:"IS"},{text:"India",value:"IN"},{text:"Indonesia",value:"ID"},{text:"Iran",value:"IR"},{text:"Iraq",value:"IQ"},{text:"IsleofMan",value:"IM"},{text:"Israel",value:"IL"},{text:"Italy",value:"IT"},{text:"IvoryCoast",value:"CI"},{text:"Jamaica",value:"JM"},{text:"Japan",value:"JP"},{text:"Jersey",value:"JE"},{text:"Jordan",value:"JO"},{text:"Kazakhstan",value:"KZ"},{text:"Kenya",value:"KE"},{text:"Kiribati",value:"KI"},{text:"Kuwait",value:"KW"},{text:"Kyrgyzstan",value:"KG"},{text:"Laos",value:"LA"},{text:"Latvia",value:"LV"},{text:"Lebanon",value:"LB"},{text:"Lesotho",value:"LS"},{text:"Liberia",value:"LR"},{text:"Libya",value:"LY"},{text:"Liechtenstein",value:"LI"},{text:"Lithuania",value:"LT"},{text:"Luxembourg",value:"LU"},{text:"Macau",value:"MO"},{text:"Madagascar",value:"MG"},{text:"Malawi",value:"MW"},{text:"Malaysia",value:"MY"},{text:"Maldives",value:"MV"},{text:"Mali",value:"ML"},{text:"Malta",value:"MT"},{text:"MarshallIslands",value:"MH"},{text:"Martinique",value:"MQ"},{text:"Mauritania",value:"MR"},{text:"Mauritius",value:"MU"},{text:"Mayotte",value:"YT"},{text:"Mexico",value:"MX"},{text:"Moldova",value:"MD"},{text:"Monaco",value:"MC"},{text:"Mongolia",value:"MN"},{text:"Montenegro",value:"ME"},{text:"Montserrat",value:"MS"},{text:"Morocco",value:"MA"},{text:"Mozambique",value:"MZ"},{text:"Myanmar",value:"MM"},{text:"Namibia",value:"NA"},{text:"Nauru",value:"NR"},{text:"Nepal",value:"NP"},{text:"Netherlands",value:"NL"},{text:"NewCaledonia",value:"NC"},{text:"NewZealand",value:"NZ"},{text:"Nicaragua",value:"NI"},{text:"Niger",value:"NE"},{text:"Nigeria",value:"NG"},{text:"Niue",value:"NU"},{text:"NorfolkIsland",value:"NF"},{text:"NorthKorea",value:"KP"},{text:"NorthMacedonia",value:"MK"},{text:"NorthernMarianaIslands",value:"MP"},{text:"Norway",value:"NO"},{text:"Oman",value:"OM"},{text:"Pakistan",value:"PK"},{text:"Palau",value:"PW"},{text:"Panama",value:"PA"},{text:"PapuaNewGuinea",value:"PG"},{text:"Paraguay",value:"PY"},{text:"Peru",value:"PE"},{text:"Philippines",value:"PH"},{text:"PitcairnIslands",value:"PN"},{text:"Poland",value:"PL"},{text:"Portugal",value:"PT"},{text:"PuertoRico",value:"PR"},{text:"Qatar",value:"QA"},{text:"RepublicofIreland",value:"IE"},{text:"RepublicoftheCongo",value:"CG"},{text:"Romania",value:"RO"},{text:"Russia",value:"RU"},{text:"Rwanda",value:"RW"},{text:"Réunion",value:"RE"},{text:"SaintBarthélemy",value:"BL"},{text:"SaintHelena",value:"SH"},{text:"SaintKittsandNevis",value:"KN"},{text:"SaintLucia",value:"LC"},{text:"SaintPierreandMiquelon",value:"PM"},{text:"SaintVincentandtheGrenadines",value:"VC"},{text:"Samoa",value:"WS"},{text:"SanMarino",value:"SM"},{text:"SaudiArabia",value:"SA"},{text:"Senegal",value:"SN"},{text:"Serbia",value:"RS"},{text:"Seychelles",value:"SC"},{text:"SierraLeone",value:"SL"},{text:"Singapore",value:"SG"},{text:"SintMaarten",value:"SX"},{text:"Slovakia",value:"SK"},{text:"Slovenia",value:"SI"},{text:"SolomonIslands",value:"SB"},{text:"Somalia",value:"SO"},{text:"SouthAfrica",value:"ZA"},{text:"SouthGeorgiaandtheSouthSandwichIslands",value:"GS"},{text:"SouthKorea",value:"KR"},{text:"SouthSudan",value:"SS"},{text:"Spain",value:"ES"},{text:"SriLanka",value:"LK"},{text:"StateofPalestine",value:"PS"},{text:"Sudan",value:"SD"},{text:"Suriname",value:"SR"},{text:"Svalbard",value:"SJ"},{text:"Sweden",value:"SE"},{text:"Switzerland",value:"CH"},{text:"Syria",value:"SY"},{text:"SãoToméandPríncipe",value:"ST"},{text:"Taiwan",value:"TW"},{text:"Tajikistan",value:"TJ"},{text:"Tanzania",value:"TZ"},{text:"Thailand",value:"TH"},{text:"TheBahamas",value:"BS"},{text:"TheGambia",value:"GM"},{text:"Togo",value:"TG"},{text:"Tokelau",value:"TK"},{text:"Tonga",value:"TO"},{text:"TrinidadandTobago",value:"TT"},{text:"Tunisia",value:"TN"},{text:"Turkey",value:"TR"},{text:"Turkmenistan",value:"TM"},{text:"TurksandCaicosIslands",value:"TC"},{text:"Tuvalu",value:"TV"},{text:"Uganda",value:"UG"},{text:"Ukraine",value:"UA"},{text:"UnitedArabEmirates",value:"AE"},{text:"UnitedKingdom",value:"GB"},{text:"UnitedStatesVirginIslands",value:"VI"},{text:"UnitedStates",value:"UM"},{text:"UnitedStates",value:"US"},{text:"Uruguay",value:"UY"},{text:"Uzbekistan",value:"UZ"},{text:"Vanuatu",value:"VU"},{text:"Venezuela",value:"VE"},{text:"Vietnam",value:"VN"},{text:"WallisandFutuna",value:"WF"},{text:"WesternSahara",value:"EH"},{text:"Yemen",value:"YE"},{text:"Zambia",value:"ZM"},{text:"Zimbabwe",value:"ZW"},{text:"ÅlandIslands",value:"AX"}] - }, + }, cursorLighting: { component: 'switch', text: 'cursorLighting', - }, + }, ads: { text: 'ads', component: 'select', @@ -72,7 +72,7 @@ extension.skeleton.main.layers.section.general = { on: { change: function (event) { const selectedValue = event.target.value; - + // Perform actions based on the selected value const numberOfSubscribersInput = this.parentNode.querySelector('.count-component'); if (selectedValue === 'small_creators') { @@ -88,20 +88,20 @@ extension.skeleton.main.layers.section.general = { class: "count-component", }, search: { - component: 'section', - variant: 'card', - title: 'Youtube_Search', - remove_related_search_results: { - component: 'switch', - text: 'removeRelatedSearchResults' - }, - open_new_tab: { - component: "switch", - text: "openNewTab", - }, - remove_shorts_reel_search_results: { - component: 'switch', - text: 'removeShortsReelSearchResults' + component: 'section', + variant: 'card', + title: 'Youtube_Search', + remove_related_search_results: { + component: 'switch', + text: 'removeRelatedSearchResults' + }, + open_new_tab: { + component: "switch", + text: "openNewTab", + }, + remove_shorts_reel_search_results: { + component: 'switch', + text: 'removeShortsReelSearchResults' } }, remove_home_page_shorts: { @@ -155,7 +155,7 @@ extension.skeleton.main.layers.section.general = { }], tags: 'trending,subscriptions,history,watch,search' } - }, + }, embed: { component: 'section', variant: 'card', @@ -183,7 +183,7 @@ extension.skeleton.main.layers.section.general = { text: 'hideAnimatedThumbnails', tags: 'preview' }, - disable_thumbnail_playback: { + disable_thumbnail_playback: { component: 'switch', text: 'disableThumbnailPlayback', }, diff --git a/menu/skeleton-parts/player.js b/menu/skeleton-parts/player.js index 4dd215948..b78fabba2 100644 --- a/menu/skeleton-parts/player.js +++ b/menu/skeleton-parts/player.js @@ -572,9 +572,9 @@ extension.skeleton.main.layers.section.player.on.click = { component: 'select', text: 'fontSize', options: [{ - text: '100%', + text: '100%', value: 0 - }, { + }, { text: '75%', value: -1 }, { @@ -586,7 +586,7 @@ extension.skeleton.main.layers.section.player.on.click = { }, { text: '200%', value: 2 - }, { + }, { text: '300%', value: 3 }, { @@ -757,11 +757,11 @@ extension.skeleton.main.layers.section.player.on.click = { }, on: { render: function () { - extension.skeleton.main.layers.section.player.on.click.section_1.player_quality.on.render.call(this); + extension.skeleton.main.layers.section.player.on.click.section_1.player_quality.on.render.call(this); } } }, -/* + /* qualityWhenRunningOnBattery: { component: 'select', text: 'qualityWhenRunningOnBattery', @@ -782,7 +782,7 @@ extension.skeleton.main.layers.section.player.on.click = { component: 'switch', text: 'pauseWhileIUnplugTheCharger' }, -*/ +*/ mini_player: { component: 'switch', text: 'customMiniPlayer' diff --git a/menu/skeleton-parts/search.js b/menu/skeleton-parts/search.js index 2f35c4053..4f8e32ce3 100644 --- a/menu/skeleton-parts/search.js +++ b/menu/skeleton-parts/search.js @@ -132,7 +132,7 @@ extension.skeleton.header.sectionEnd.search.on.click = { self.setAttribute('results', ''); search_results = satus.render(skeleton, self.baseProvider); - + // we need global listener here function hidesearch(event) { // make sure to clean it after closing search results @@ -155,7 +155,7 @@ extension.skeleton.header.sectionEnd.search.on.click = { } document.addEventListener('click', hidesearch); - + if (self.skeleton.searchPosition) { search_results.childNodes[1].scrollTop = self.skeleton.searchPosition; } diff --git a/menu/skeleton-parts/themes.js b/menu/skeleton-parts/themes.js index 01436c4ae..506a31c50 100644 --- a/menu/skeleton-parts/themes.js +++ b/menu/skeleton-parts/themes.js @@ -51,10 +51,10 @@ extension.skeleton.main.layers.section.themes.on.click.section = { variant: satus.storage.get('theme') == 'dark' ? 'dark-theme' : 'default-theme', text: satus.storage.get('theme') == 'dark' ? 'youtubesDark' : 'youtubesLight', radio: { - component: 'radio', - group: 'theme', - value: satus.storage.get('theme') == 'dark' ? 'dark' : 'light', - ...(!satus.storage.get('theme') && { checked: true }) + component: 'radio', + group: 'theme', + value: satus.storage.get('theme') == 'dark' ? 'dark' : 'light', + ...(!satus.storage.get('theme') && { checked: true }) } } }, @@ -64,10 +64,10 @@ extension.skeleton.main.layers.section.themes.on.click.section = { variant: satus.storage.get('theme') == 'dark' ? 'default-theme' : 'dark-theme', text: satus.storage.get('theme') == 'dark' ? 'youtubesLight' : 'youtubesDark', radio: { - component: 'radio', - group: 'theme', - value: satus.storage.get('theme') == 'dark' ? 'light' : 'dark', - ...(satus.storage.get('theme') == 'dark' && { checked: true }) + component: 'radio', + group: 'theme', + value: satus.storage.get('theme') == 'dark' ? 'light' : 'dark', + ...(satus.storage.get('theme') == 'dark' && { checked: true }) } } }, diff --git a/menu/skeleton.js b/menu/skeleton.js index 19c6ec188..61dc6b683 100644 --- a/menu/skeleton.js +++ b/menu/skeleton.js @@ -77,7 +77,7 @@ extension.skeleton.header = { 'fill': 'none' }, id: 'dark-light-switch-icon-sun', - + circle: { component: 'circle', attr: { diff --git a/unit/core.test.js b/unit/core.test.js index 57b6ee067..21195bde4 100644 --- a/unit/core.test.js +++ b/unit/core.test.js @@ -38,21 +38,21 @@ jest.mock('../../js&css/extension/core', () => ({ trigger: async function (type, data) { const listeners = this.listeners[type]; - if (listeners) { - for (let i = 0, l = listeners.length; i < l; i++) { - const listener = listeners[i]; - - if (typeof listener === 'function') { - if (listener instanceof (async function () { }).constructor === true) { - await listener(data); - } else { - listener(data); - } - } - } - } - }, - }, + if (listeners) { + for (let i = 0, l = listeners.length; i < l; i++) { + const listener = listeners[i]; + + if (typeof listener === 'function') { + if (listener instanceof (async function () { }).constructor === true) { + await listener(data); + } else { + listener(data); + } + } + } + } + }, + }, })); @@ -62,58 +62,58 @@ const extensionMock = require('../js&css/extension/core'); // Unit tests for the camelize function test('Convert snake_case to camelCase', () => { - const input = 'snake_case_example'; - const expectedOutput = 'snakeCaseExample'; + const input = 'snake_case_example'; + const expectedOutput = 'snakeCaseExample'; - const mockInput = extensionMock.camelize(input); + const mockInput = extensionMock.camelize(input); - expect(mockInput).toBe(expectedOutput); + expect(mockInput).toBe(expectedOutput); }); test('Convert kebab-case to camelCase', () => { - // Define input and expected output - const input = 'kebab-case-example'; - const expectedOutput = 'kebabCaseExample'; + // Define input and expected output + const input = 'kebab-case-example'; + const expectedOutput = 'kebabCaseExample'; - // Call the camelize function with the input - const mockInput = extensionMock.camelize(input); + // Call the camelize function with the input + const mockInput = extensionMock.camelize(input); - // Check if the result matches the expected output - expect(mockInput).toBe(expectedOutput); + // Check if the result matches the expected output + expect(mockInput).toBe(expectedOutput); }); // Unit test for the events method test('Trigger method should correctly retrieve and invoke listeners', () => { - // Mock event listeners - const listener1 = jest.fn(); - const listener2 = jest.fn(); - const listener3 = jest.fn(); + // Mock event listeners + const listener1 = jest.fn(); + const listener2 = jest.fn(); + const listener3 = jest.fn(); - // Register listeners for a specific event type - extensionMock.events.listeners['eventType'] = [listener1, listener2, listener3]; + // Register listeners for a specific event type + extensionMock.events.listeners['eventType'] = [listener1, listener2, listener3]; - // Call the trigger method with the event type and data - extensionMock.events.trigger('eventType', { data: 'example' }); + // Call the trigger method with the event type and data + extensionMock.events.trigger('eventType', { data: 'example' }); - // Verify that each listener is invoked with the provided data - expect(listener1).toHaveBeenCalledWith({ data: 'example' }); - expect(listener2).toHaveBeenCalledWith({ data: 'example' }); - expect(listener3).toHaveBeenCalledWith({ data: 'example' }); + // Verify that each listener is invoked with the provided data + expect(listener1).toHaveBeenCalledWith({ data: 'example' }); + expect(listener2).toHaveBeenCalledWith({ data: 'example' }); + expect(listener3).toHaveBeenCalledWith({ data: 'example' }); }); test('Trigger method should handle asynchronous listeners', async () => { - // Mock asynchronous event listeners - const asyncListener = jest.fn().mockImplementation(async () => { - // Simulate asynchronous behavior - await new Promise(resolve => setTimeout(resolve, 100)); - }); + // Mock asynchronous event listeners + const asyncListener = jest.fn().mockImplementation(async () => { + // Simulate asynchronous behavior + await new Promise(resolve => setTimeout(resolve, 100)); + }); - // Register the asynchronous listener for a specific event type - extensionMock.events.listeners['eventType'] = [asyncListener]; + // Register the asynchronous listener for a specific event type + extensionMock.events.listeners['eventType'] = [asyncListener]; - // Call the trigger method with the event type and data - await extensionMock.events.trigger('eventType', { data: 'example' }); + // Call the trigger method with the event type and data + await extensionMock.events.trigger('eventType', { data: 'example' }); - // Verify that the asynchronous listener is invoked with the provided data - expect(asyncListener).toHaveBeenCalledWith({ data: 'example' }); + // Verify that the asynchronous listener is invoked with the provided data + expect(asyncListener).toHaveBeenCalledWith({ data: 'example' }); }); From e353e2b251870e82df197b2cdeaea95214052ddf Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 20:51:39 +0800 Subject: [PATCH 06/17] Fix jest test not working --- unit/core.test.js => core.test.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename unit/core.test.js => core.test.js (100%) diff --git a/unit/core.test.js b/core.test.js similarity index 100% rename from unit/core.test.js rename to core.test.js From 0dc5a4af84f8cfef2fc35f29d80373b05ffe4038 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 20:54:32 +0800 Subject: [PATCH 07/17] Fix jest test not working --- core.test.js => tests/unit/core.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core.test.js => tests/unit/core.test.js (98%) diff --git a/core.test.js b/tests/unit/core.test.js similarity index 98% rename from core.test.js rename to tests/unit/core.test.js index 21195bde4..280e0db5c 100644 --- a/core.test.js +++ b/tests/unit/core.test.js @@ -57,7 +57,7 @@ jest.mock('../../js&css/extension/core', () => ({ })); // Mock extension object -const extensionMock = require('../js&css/extension/core'); +const extensionMock = require('./js&css/extension/core'); // Unit tests for the camelize function test('Convert snake_case to camelCase', () => { From 76c65ec919ea69bf4170575db8c6d605aa41d2d4 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 20:57:27 +0800 Subject: [PATCH 08/17] Update core.test.js --- tests/unit/core.test.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/unit/core.test.js b/tests/unit/core.test.js index 280e0db5c..f1e23dbff 100644 --- a/tests/unit/core.test.js +++ b/tests/unit/core.test.js @@ -1,6 +1,11 @@ // Mock extension object directly within the jest.mock call jest.mock('../../js&css/extension/core', () => ({ domReady: false, + events: { + listeners: {}, + on: jest.fn(), + trigger: jest.fn(), + }, features: {}, functions: {}, messages: { @@ -34,7 +39,6 @@ jest.mock('../../js&css/extension/core', () => ({ events: { // Mock implementation of the events function listeners: {}, - on: jest.fn(), trigger: async function (type, data) { const listeners = this.listeners[type]; @@ -57,7 +61,7 @@ jest.mock('../../js&css/extension/core', () => ({ })); // Mock extension object -const extensionMock = require('./js&css/extension/core'); +const extensionMock = require('../../js&css/extension/core'); // Unit tests for the camelize function test('Convert snake_case to camelCase', () => { @@ -116,4 +120,4 @@ test('Trigger method should handle asynchronous listeners', async () => { // Verify that the asynchronous listener is invoked with the provided data expect(asyncListener).toHaveBeenCalledWith({ data: 'example' }); -}); +}); \ No newline at end of file From 8280e4652b236e9b3e6489881bc86f940a13f12e Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 20:59:30 +0800 Subject: [PATCH 09/17] Remove JSLint --- .github/workflows/{js-lint-test.yml => lint-test.yml} | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) rename .github/workflows/{js-lint-test.yml => lint-test.yml} (82%) diff --git a/.github/workflows/js-lint-test.yml b/.github/workflows/lint-test.yml similarity index 82% rename from .github/workflows/js-lint-test.yml rename to .github/workflows/lint-test.yml index 856fcdcab..6d19ce8ee 100644 --- a/.github/workflows/js-lint-test.yml +++ b/.github/workflows/lint-test.yml @@ -26,13 +26,13 @@ jobs: - name: Install dependencies run: npm install - - name: Install dependencies + - name: Run eslint run: npx eslint continue-on-error: true - - name: Run JSLint - run: npx jslint "**/*.js" - continue-on-error: true + # - name: Run JSLint + # run: npx jslint "**/*.js" + # continue-on-error: true - name: Run Jest run: npx jest From d23c5df877f1290aa4180cab82ee925f70594c98 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 21:01:05 +0800 Subject: [PATCH 10/17] Revert workflow name --- .github/workflows/{lint-test.yml => js-lint-test.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{lint-test.yml => js-lint-test.yml} (100%) diff --git a/.github/workflows/lint-test.yml b/.github/workflows/js-lint-test.yml similarity index 100% rename from .github/workflows/lint-test.yml rename to .github/workflows/js-lint-test.yml From 9cdb2853cdab16229083555c8746f011275bec80 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 22:47:47 +0800 Subject: [PATCH 11/17] Add no-multiple-empty-lines check --- eslint.config.mjs | 1 + js&css/extension/core.js | 5 --- .../www.youtube.com/general/general.js | 7 ---- .../www.youtube.com/night-mode/night-mode.js | 2 - js&css/web-accessible/functions.js | 2 - js&css/web-accessible/init.js | 1 - .../web-accessible/www.youtube.com/player.js | 2 - .../www.youtube.com/settings.js | 2 - menu/functions.js | 3 -- menu/satus.js | 41 ------------------- menu/skeleton-parts/appearance.js | 3 -- menu/skeleton-parts/settings.js | 5 --- 12 files changed, 1 insertion(+), 73 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index db5da1eb4..2583e92c8 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -38,6 +38,7 @@ export default [...compat.extends("eslint:recommended"), { "no-multi-spaces": "warn", "no-fallthrough": ["error", { "allowEmptyCase": true }], "no-implicit-globals": "error", + "no-multiple-empty-lines": ["error", {"max": 1, "maxBOF": 0, "maxEOF": 0}], "max-len": ["error", { code: 255, ignoreUrls: true, diff --git a/js&css/extension/core.js b/js&css/extension/core.js index f368ae817..2b92f6bc8 100644 --- a/js&css/extension/core.js +++ b/js&css/extension/core.js @@ -37,7 +37,6 @@ var extension = { } }; - /*-------------------------------------------------------------- # CAMELIZE --------------------------------------------------------------*/ @@ -60,7 +59,6 @@ extension.camelize = function (string) { return result; }; - /*-------------------------------------------------------------- # EVENTS --------------------------------------------------------------*/ @@ -91,7 +89,6 @@ extension.events.on = function (type, listener, options = {}) { } }; - /*-------------------------------------------------------------- # TRIGGER --------------------------------------------------------------*/ @@ -178,7 +175,6 @@ extension.inject = function (paths, callback) { } };*/ - /*-------------------------------------------------------------- # MESSAGES ---------------------------------------------------------------- @@ -234,7 +230,6 @@ extension.messages.send = function (message) { } }; - /*-------------------------------------------------------------- # STORAGE --------------------------------------------------------------*/ diff --git a/js&css/extension/www.youtube.com/general/general.js b/js&css/extension/www.youtube.com/general/general.js index 9ce6ef88c..f93509cb4 100644 --- a/js&css/extension/www.youtube.com/general/general.js +++ b/js&css/extension/www.youtube.com/general/general.js @@ -136,7 +136,6 @@ extension.features.collapseOfSubscriptionSections = function (event) { } }; - /*-------------------------------------------------------------- # ONLY ONE PLAYER INSTANCE PLAYING --------------------------------------------------------------*/ @@ -197,7 +196,6 @@ extension.features.confirmationBeforeClosing = function () { }; }; - /*-------------------------------------------------------------- # DEFAULT CONTENT COUNTRY --------------------------------------------------------------*/ @@ -222,7 +220,6 @@ extension.features.defaultContentCountry = function (changed) { } }; - /*-------------------------------------------------------------- # ADD "POPUP WINDOW" BUTTONS --------------------------------------------------------------*/ @@ -321,7 +318,6 @@ extension.features.font = function (changed) { } }; - /*-------------------------------------------------------------- # MARK WATCHED VIDEOS --------------------------------------------------------------*/ @@ -419,7 +415,6 @@ extension.features.markWatchedVideos = function (anything) { } }; - /*-------------------------------------------------------------- # TRACK WATCHED VIDEOS --------------------------------------------------------------*/ @@ -442,7 +437,6 @@ extension.features.trackWatchedVideos = function () { } }; - /*-------------------------------------------------------------- # THUMBNAILS QUALITY --------------------------------------------------------------*/ @@ -549,7 +543,6 @@ extension.features.openNewTab = function (){ } }); - let searchedAlready = false; inputField.addEventListener("focus", function () { searchedAlready = false; diff --git a/js&css/extension/www.youtube.com/night-mode/night-mode.js b/js&css/extension/www.youtube.com/night-mode/night-mode.js index 8fb89c805..084a4e843 100644 --- a/js&css/extension/www.youtube.com/night-mode/night-mode.js +++ b/js&css/extension/www.youtube.com/night-mode/night-mode.js @@ -76,7 +76,6 @@ extension.features.bluelight = function () { } }; - /*-------------------------------------------------------------- # DIM --------------------------------------------------------------*/ @@ -107,7 +106,6 @@ extension.features.dim = function () { } }; - /*-------------------------------------------------------------- # SCHEDULE --------------------------------------------------------------*/ diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index 88c3a85ef..96f14ace1 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -98,7 +98,6 @@ ImprovedTube.ytElementsHandler = function (node) { this.improvedtubeYoutubeIcon(); this.improvedtubeYoutubeButtonsUnderPlayer(); - } else if (name === 'YTD-VIDEO-SECONDARY-INFO-RENDERER') { this.elements.yt_channel_name = node.querySelector('ytd-channel-name'); this.elements.yt_channel_link = node.querySelector('ytd-channel-name a'); @@ -642,7 +641,6 @@ ImprovedTube.showStatus = function (value) { ImprovedTube.videoId = function (url = document.URL) {return url.match(ImprovedTube.regex.video_id)[1] || url.searchParams.get('v') || movie_player.getVideoData().video_id}; ImprovedTube.videoTitle = function () {return document.title?.replace(/\s*-\s*YouTube$/, '') || movie_player.getVideoData().title || document.querySelector('#title > h1 > *')?.textContent}; - // Function to extract and store the number of subscribers ImprovedTube.extractSubscriberCount = function (subscriberCountNode) { if (!subscriberCountNode) {subscriberCountNode = document.getElementById('owner-sub-count');} diff --git a/js&css/web-accessible/init.js b/js&css/web-accessible/init.js index 329946a26..2bd172ed4 100644 --- a/js&css/web-accessible/init.js +++ b/js&css/web-accessible/init.js @@ -54,7 +54,6 @@ ImprovedTube.observer = new MutationObserver(function (mutationList) { i++;} */ - }).observe(document.documentElement, { // attributes: true, // attributeOldValue: true, diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index f3aab0e5e..7075d3d51 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -809,7 +809,6 @@ ImprovedTube.playerFitToWinButton = function () { } }; - /*------------------------------------------------------------------------------ CINEMA MODE BUTTON ------------------------------------------------------------------------------*/ @@ -866,7 +865,6 @@ ImprovedTube.playerCinemaModeButton = function () { svg.parentNode.style.opacity = 1; } - var overlay = document.getElementById('overlay_cinema'); if (!overlay) { createOverlay(); diff --git a/js&css/web-accessible/www.youtube.com/settings.js b/js&css/web-accessible/www.youtube.com/settings.js index 60149aa35..25348beba 100644 --- a/js&css/web-accessible/www.youtube.com/settings.js +++ b/js&css/web-accessible/www.youtube.com/settings.js @@ -145,7 +145,6 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { } }; - /*----------------------------------------------------------------------------- 4.10.3 DELETE YOUTUBE COOKIES -----------------------------------------------------------------------------*/ @@ -164,7 +163,6 @@ ImprovedTube.deleteYoutubeCookies = function () { setTimeout(function () {location.reload();}, 100); }; - /*----------------------------------------------------------------------------- 4.10.4 YOUTUBE LANGUAGE -----------------------------------------------------------------------------*/ diff --git a/menu/functions.js b/menu/functions.js index 11c011c98..6dff508a1 100644 --- a/menu/functions.js +++ b/menu/functions.js @@ -44,7 +44,6 @@ extension.attributes = function () { } }; - /*-------------------------------------------------------------- # EXPORT SETTINGS --------------------------------------------------------------*/ @@ -101,7 +100,6 @@ extension.exportSettings = function () { } }; - /*-------------------------------------------------------------- # IMPORT SETTINGS --------------------------------------------------------------*/ @@ -163,7 +161,6 @@ extension.importSettings = function () { } }; - /*-------------------------------------------------------------- # sync SETTINGS --------------------------------------------------------------*/ diff --git a/menu/satus.js b/menu/satus.js index 3bd5917be..83f81f6c6 100644 --- a/menu/satus.js +++ b/menu/satus.js @@ -32,7 +32,6 @@ fetch(url, success, error, type) indexOf(child, parent) toIndex(index, child, parent) - # ON: on(element, listeners) parentify(parentObject, exclude) @@ -103,8 +102,6 @@ RGB2HSL HUE2RGB HSL2RGB // TO-DO or integrate with JS search libs --------------------------------------------------------------*/ - - /*-------------------------------------------------------------- # GLOBAL VARIABLE --------------------------------------------------------------*/ @@ -256,10 +253,8 @@ satus.log =function(){console.log.apply(null, arguments);}; /*-------------------------------------------------------------- - # DOM - --------------------------------------------------------------*/ /*-------------------------------------------------------------- # APPEND @@ -391,10 +386,8 @@ satus.elementIndex = function(element) { /*-------------------------------------------------------------- - # CSS - --------------------------------------------------------------*/ satus.css = function(element, property) { return window.getComputedStyle(element).getPropertyValue(property); @@ -424,7 +417,6 @@ satus.getAnimationDuration = function(element) { return Number(window.getComputedStyle(element).getPropertyValue('animation-duration').replace(/[^0-9.]/g, '')) * 1000; }; - /*-------------------------------------------------------------- # CRYPTION @@ -476,7 +468,6 @@ satus.encrypt = async function(text, password) { /*-------------------------------------------------------------- # EVENTS - --------------------------------------------------------------*/ /*-- ON ------------------------------------------------------*/ satus.events.on = function(type, handler) { @@ -526,7 +517,6 @@ satus.getProperty = function(object, string) { } }; - /*-------------------------------------------------------------- # INDEX OF --------------------------------------------------------------*/ @@ -545,7 +535,6 @@ satus.indexOf = function(child, parent) { return index; }; - /*-------------------------------------------------------------- # TO INDEX --------------------------------------------------------------*/ @@ -630,7 +619,6 @@ satus.on = function(element, listeners) { } }; - /*-------------------------------------------------------------- # PARENTIFY --------------------------------------------------------------*/ @@ -859,10 +847,8 @@ satus.render = function(skeleton, container, property, childrenOnly, prepend, sk /*-------------------------------------------------------------- - # STORAGE - --------------------------------------------------------------*/ /*-------------------------------------------------------------- # CLEAR @@ -880,7 +866,6 @@ satus.storage.clear = function(callback) { }); }; - /*-------------------------------------------------------------- # GET --------------------------------------------------------------*/ @@ -911,7 +896,6 @@ satus.storage.get = function(key) { } }; - /*-------------------------------------------------------------- # IMPORT --------------------------------------------------------------*/ @@ -1022,7 +1006,6 @@ satus.storage.onchanged = function(callback) { }); }; - /*-------------------------------------------------------------- # LAST --------------------------------------------------------------*/ @@ -1033,7 +1016,6 @@ satus.last = function(variable) { } }; - /*-------------------------------------------------------------- # LOCALIZATION @@ -1533,7 +1515,6 @@ satus.components.chart = function(component, skeleton) { } }; - /*-------------------------------------------------------------- # BAR --------------------------------------------------------------*/ @@ -2704,7 +2685,6 @@ satus.manifest = function() { satus.color = {}; - /*-------------------------------------------------------------- # STRING TO ARRAY --------------------------------------------------------------*/ @@ -2721,7 +2701,6 @@ satus.color.stringToArray = function(string) { return match; }; - /*-------------------------------------------------------------- # RGB TO HSL --------------------------------------------------------------*/ @@ -2766,7 +2745,6 @@ satus.color.rgbToHsl = function(array) { } }; - /*-------------------------------------------------------------- # HUE TO RGB --------------------------------------------------------------*/ @@ -2795,7 +2773,6 @@ satus.color.hueToRgb = function(array) { } }; - /*-------------------------------------------------------------- # HSL TO RGB --------------------------------------------------------------*/ @@ -2904,7 +2881,6 @@ satus.user.os.name = function() { } }; - /*-------------------------------------------------------------- # BITNESS --------------------------------------------------------------*/ @@ -2917,7 +2893,6 @@ satus.user.os.bitness = function() { } }; - /*-------------------------------------------------------------- # BROWSER --------------------------------------------------------------*/ @@ -2949,7 +2924,6 @@ satus.user.browser.name = function() { } }; - /*-------------------------------------------------------------- # VERSION --------------------------------------------------------------*/ @@ -2961,7 +2935,6 @@ satus.user.browser.version = function() { return browser_version[1]; }; - /*-------------------------------------------------------------- # PLATFORM --------------------------------------------------------------*/ @@ -2970,7 +2943,6 @@ satus.user.browser.platform = function() { return navigator.platform; }; - /*-------------------------------------------------------------- # MANIFEST --------------------------------------------------------------*/ @@ -2979,7 +2951,6 @@ satus.user.browser.manifest = function() { return chrome.runtime.getManifest() || {}; }; - /*-------------------------------------------------------------- # LANGUAGES --------------------------------------------------------------*/ @@ -2988,7 +2959,6 @@ satus.user.browser.languages = function() { return navigator.languages; }; - /*-------------------------------------------------------------- # COOKIES --------------------------------------------------------------*/ @@ -3007,7 +2977,6 @@ satus.user.browser.cookies = function() { return false; }; - /*-------------------------------------------------------------- # FLASH --------------------------------------------------------------*/ @@ -3026,7 +2995,6 @@ satus.user.browser.flash = function() { return false; }; - /*-------------------------------------------------------------- # JAVA --------------------------------------------------------------*/ @@ -3039,7 +3007,6 @@ satus.user.browser.java = function() { } }; - /*-------------------------------------------------------------- # AUDIO --------------------------------------------------------------*/ @@ -3068,7 +3035,6 @@ satus.user.browser.audio = function() { return result; }; - /*-------------------------------------------------------------- # VIDEO --------------------------------------------------------------*/ @@ -3099,7 +3065,6 @@ satus.user.browser.video = function() { return result; }; - /*-------------------------------------------------------------- # WEBGL --------------------------------------------------------------*/ @@ -3111,7 +3076,6 @@ satus.user.browser.webgl = function() { return ctx && ctx instanceof WebGLRenderingContext; }; - /*-------------------------------------------------------------- # HARDWARE --------------------------------------------------------------*/ @@ -3126,7 +3090,6 @@ satus.user.device.screen = function() { } }; - /*-------------------------------------------------------------- # RAM --------------------------------------------------------------*/ @@ -3137,7 +3100,6 @@ satus.user.device.ram = function() { } }; - /*-------------------------------------------------------------- # GPU --------------------------------------------------------------*/ @@ -3160,7 +3122,6 @@ satus.user.device.gpu = function() { } }; - /*-------------------------------------------------------------- # CORES --------------------------------------------------------------*/ @@ -3169,7 +3130,6 @@ satus.user.device.cores = function() { return navigator.deviceConcurrency || navigator.hardwareConcurrency; }; - /*-------------------------------------------------------------- # TOUCH --------------------------------------------------------------*/ @@ -3190,7 +3150,6 @@ satus.user.device.touch = function() { return result; }; - /*-------------------------------------------------------------- # CONNECTION --------------------------------------------------------------*/ diff --git a/menu/skeleton-parts/appearance.js b/menu/skeleton-parts/appearance.js index 066a45efe..9711cbef8 100644 --- a/menu/skeleton-parts/appearance.js +++ b/menu/skeleton-parts/appearance.js @@ -411,7 +411,6 @@ extension.skeleton.main.layers.section.appearance.on.click.player = { # DETAILS --------------------------------------------------------------*/ - extension.skeleton.main.layers.section.appearance.on.click.details = { component: "button", variant: "details", @@ -719,7 +718,6 @@ extension.skeleton.main.layers.section.appearance.on.click.hide_detail_button = } } - /*-------------------------------------------------------------- # COMMENTS --------------------------------------------------------------*/ @@ -797,7 +795,6 @@ extension.skeleton.main.layers.section.appearance.on.click.popup_ad = { tags: "bottom" }; - /*-------------------------------------------------------------- # SIDEBAR --------------------------------------------------------------*/ diff --git a/menu/skeleton-parts/settings.js b/menu/skeleton-parts/settings.js index 484eab3b1..aa4af84e9 100644 --- a/menu/skeleton-parts/settings.js +++ b/menu/skeleton-parts/settings.js @@ -59,7 +59,6 @@ extension.skeleton.header.sectionEnd.menu.on.click.settings = { } }; - /*-------------------------------------------------------------- # APPEARANCE --------------------------------------------------------------*/ @@ -188,7 +187,6 @@ extension.skeleton.header.sectionEnd.menu.on.click.settings.on.click.firstSectio } }; - /*-------------------------------------------------------------- # LANGUAGE --------------------------------------------------------------*/ @@ -348,7 +346,6 @@ extension.skeleton.header.sectionEnd.menu.on.click.settings.on.click.secondSecti } }; - /*-------------------------------------------------------------- # BACKUP & RESET --------------------------------------------------------------*/ @@ -555,7 +552,6 @@ extension.skeleton.header.sectionEnd.menu.on.click.settings.on.click.secondSecti } }; - /*-------------------------------------------------------------- # DEVELOPER OPTIONS --------------------------------------------------------------*/ @@ -631,7 +627,6 @@ extension.skeleton.header.sectionEnd.menu.on.click.settings.on.click.secondSecti } }; - /*-------------------------------------------------------------- # ABOUT --------------------------------------------------------------*/ From 1e8277b37aaf8dbe5d4cc38fa9dfffd911ed4a37 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 22:56:55 +0800 Subject: [PATCH 12/17] Added semi-spacing and comma-spacing check --- background.js | 6 +++--- eslint.config.mjs | 2 ++ js&css/web-accessible/functions.js | 2 +- .../www.youtube.com/appearance.js | 6 +++--- .../www.youtube.com/blocklist.js | 2 +- .../web-accessible/www.youtube.com/player.js | 10 +++++----- .../web-accessible/www.youtube.com/settings.js | 2 +- .../www.youtube.com/shortcuts.js | 18 +++++++++--------- menu/skeleton-parts/general.js | 6 +++--- 9 files changed, 28 insertions(+), 26 deletions(-) diff --git a/background.js b/background.js index 441a17ff3..0a042f68c 100644 --- a/background.js +++ b/background.js @@ -37,7 +37,7 @@ chrome.runtime.onInstalled.addListener(function (installed) { if (!keys) continue; let newKeys = {}, newName = name.replace('shortcut_', 'shortcut_quality_'); - for (const button of ['alt','ctrl','shift','wheel','toggle']) { + for (const button of ['alt', 'ctrl', 'shift', 'wheel', 'toggle']) { if (keys[button]) newKeys[button] = keys[button]; } if (keys['keys'] && Object.keys(keys['keys'])?.length) { @@ -110,11 +110,11 @@ chrome.runtime.onInstalled.addListener(function (installed) { --------------------------------------------------------------*/ function getLocale(language, callback) { language = language.replace('-', '_'); - fetch('_locales/' + language.substring(0,2) + '/messages.json').then(function (response) { + fetch('_locales/' + language.substring(0, 2) + '/messages.json').then(function (response) { if (response.ok) { response.json().then(callback); } else { - fetch('_locales/' + language.substring(0,2) + '/messages.json').then(function (response) { + fetch('_locales/' + language.substring(0, 2) + '/messages.json').then(function (response) { if (response.ok) { response.json().then(callback); } else { diff --git a/eslint.config.mjs b/eslint.config.mjs index 2583e92c8..5f7f919d5 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -36,6 +36,8 @@ export default [...compat.extends("eslint:recommended"), { "no-undef": ["off"], "no-trailing-spaces": "warn", "no-multi-spaces": "warn", + "semi-spacing": "error", + "comma-spacing": "error", "no-fallthrough": ["error", { "allowEmptyCase": true }], "no-implicit-globals": "error", "no-multiple-empty-lines": ["error", {"max": 1, "maxBOF": 0, "maxEOF": 0}], diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index 96f14ace1..4b3186398 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -431,7 +431,7 @@ ImprovedTube.onkeydown = function () { ImprovedTube.onmousedown = function () { window.addEventListener('mousedown', function (event) { if (!ImprovedTube.user_interacted) { - setTimeout(function(){ImprovedTube.user_interacted = true},3000); + setTimeout(function(){ImprovedTube.user_interacted = true}, 3000); if (ImprovedTube.elements.player && ImprovedTube.elements.player.classList.contains('ad-showing') === false) { var path = event.composedPath(); for (var i = 0, l = path.length; i < l; i++) { diff --git a/js&css/web-accessible/www.youtube.com/appearance.js b/js&css/web-accessible/www.youtube.com/appearance.js index 272c26ca4..ee1fb8d0b 100644 --- a/js&css/web-accessible/www.youtube.com/appearance.js +++ b/js&css/web-accessible/www.youtube.com/appearance.js @@ -243,8 +243,8 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid if (!navigator.userAgent.toLowerCase().includes("mac")){ let color, colorHover const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; - if(isDarkMode) [color,colorHover] = ["#616161", "#909090"]; - else [color,colorHover] = ["#aaaaaa", "#717171"]; + if(isDarkMode) [color, colorHover] = ["#616161", "#909090"]; + else [color, colorHover] = ["#aaaaaa", "#717171"]; const style = document.createElement("style"); if(ImprovedTube.storage.comments_sidebar_scrollbars === true){ const cssRule = ` @@ -431,7 +431,7 @@ ImprovedTube.expandDescription = function (el) { var waitForDescription = setInterval(() => { if (++tries >= maxTries) { el = document.querySelector('#description-inline-expander') - if ( el) { el.click(); setTimeout(function(){ImprovedTube.elements.player.focus(); }, 1200);clearInterval(waitForDescription); } + if ( el) { el.click(); setTimeout(function(){ImprovedTube.elements.player.focus(); }, 1200); clearInterval(waitForDescription); } intervalMs *= 1.11; }}, intervalMs); } } diff --git a/js&css/web-accessible/www.youtube.com/blocklist.js b/js&css/web-accessible/www.youtube.com/blocklist.js index 2d9f20bcc..e3b82abe1 100644 --- a/js&css/web-accessible/www.youtube.com/blocklist.js +++ b/js&css/web-accessible/www.youtube.com/blocklist.js @@ -228,7 +228,7 @@ ImprovedTube.blocklistObserver = new MutationObserver(function (mutationList) { }); ImprovedTube.blocklistElementTypeHelper = function (node) { - switch(node.parentNode.className.replace('style-scope ','')) { + switch(node.parentNode.className.replace('style-scope ', '')) { case 'ytd-compact-video-renderer': // list next to player // node.parentNode.__dataHost.$.dismissible; diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index 7075d3d51..6b8820783 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -213,7 +213,7 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { ImprovedTube.fetchDOMData();} else { //Invidious instances. Should be updated automatically!... - const invidiousInstances = ['invidious.fdn.fr','inv.tux.pizza','invidious.flokinet.to','invidious.protokolla.fi','invidious.private.coffee','yt.artemislena.eu','invidious.perennialte.ch','invidious.materialio.us','iv.datura.network']; + const invidiousInstances = ['invidious.fdn.fr', 'inv.tux.pizza', 'invidious.flokinet.to', 'invidious.protokolla.fi', 'invidious.private.coffee', 'yt.artemislena.eu', 'invidious.perennialte.ch', 'invidious.materialio.us', 'iv.datura.network']; function getRandomInvidiousInstance() { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} (async function () { let retries = 4; let invidiousFetched = false; @@ -356,7 +356,7 @@ ImprovedTube.subtitlesDisableLyrics = function () { if (player && player.isSubtitlesOn && player.isSubtitlesOn() && player.toggleSubtitles) { // Music detection only uses 3 identifiers for Lyrics: lyrics, sing-along, karaoke. // Easier to simply use those here. Can replace with music detection later. - const terms = ["sing along", "sing-along", "karaoke", "lyric", "卡拉OK", "卡拉OK", "الكاريوكي", "караоке", "カラオケ","노래방"]; + const terms = ["sing along", "sing-along", "karaoke", "lyric", "卡拉OK", "卡拉OK", "الكاريوكي", "караоке", "カラオケ", "노래방"]; if (terms.some(term => this.videoTitle().toLowerCase().includes(term))) { player.toggleSubtitles(); } @@ -608,7 +608,7 @@ ImprovedTube.screenshot = function () { let captionElements = document.querySelectorAll('.captions-text .ytp-caption-segment'); captionElements.forEach(function (caption) {subText += caption.textContent.trim() + ' ';}); - ImprovedTube.renderSubtitle(ctx,captionElements); + ImprovedTube.renderSubtitle(ctx, captionElements); } cvs.toBlob(function (blob) { @@ -634,7 +634,7 @@ ImprovedTube.screenshot = function () { }); }; -ImprovedTube.renderSubtitle = function (ctx,captionElements) { +ImprovedTube.renderSubtitle = function (ctx, captionElements) { if (ctx && captionElements) { captionElements.forEach(function (captionElement, index) { var captionText = captionElement.textContent.trim(); @@ -816,7 +816,7 @@ CINEMA MODE BUTTON var xpath = function(xpathToExecute){ var result = []; var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); - for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ ){ + for ( var i=0; i < nodesSnapshot.snapshotLength; i++ ){ result.push( nodesSnapshot.snapshotItem(i) ); } return result; diff --git a/js&css/web-accessible/www.youtube.com/settings.js b/js&css/web-accessible/www.youtube.com/settings.js index 25348beba..d2ae70ba8 100644 --- a/js&css/web-accessible/www.youtube.com/settings.js +++ b/js&css/web-accessible/www.youtube.com/settings.js @@ -45,7 +45,7 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { } function mouseup() { - localStorage.setItem('improvedtube-button-position', JSON.stringify({x,y})); + localStorage.setItem('improvedtube-button-position', JSON.stringify({x, y})); window.removeEventListener('mousemove', mousemove); window.removeEventListener('mouseup', mouseup); diff --git a/js&css/web-accessible/www.youtube.com/shortcuts.js b/js&css/web-accessible/www.youtube.com/shortcuts.js index de0c26fe0..be822f93c 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -8,7 +8,7 @@ WARNING: Browser Debugger Breakpoint downstream from keydown() event will eat co ------------------------------------------------------------------------------*/ ImprovedTube.shortcuts = function () { const ignoreElements = ['EMBED', 'INPUT', 'OBJECT', 'TEXTAREA', 'IFRAME'], - modifierKeys = ['AltLeft','AltRight','ControlLeft','ControlRight','ShiftLeft','ShiftRight'], + modifierKeys = ['AltLeft', 'AltRight', 'ControlLeft', 'ControlRight', 'ShiftLeft', 'ShiftRight'], handlers = { keydown: function (event) { if (document.activeElement && ignoreElements.includes(document.activeElement.tagName) || event.target.isContentEditable) return; @@ -106,7 +106,7 @@ ImprovedTube.shortcuts = function () { // camelCase(name) const camelName = name.replace(/_(.)/g, (m, l) => l.toUpperCase()); let potentialShortcut = {}; - for (const button of ['alt','ctrl','shift','wheel','keys']) { + for (const button of ['alt', 'ctrl', 'shift', 'wheel', 'keys']) { switch(button) { case 'alt': case 'ctrl': @@ -446,18 +446,18 @@ ImprovedTube.shortcutDislike = function () { /*------Report------*/ ImprovedTube.shortcutReport = function () { try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); - document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} - catch{console.log("'...' failed"); setTimeout(function(){try{document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} - catch{console.log("'...' failed2")}},100) } + document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} + catch{console.log("'...' failed"); setTimeout(function(){try{document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} + catch{console.log("'...' failed2")}}, 100) } setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} - catch{console.log("report failed");setTimeout(function() {try{document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} - catch{console.log("report failed2");document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}},800); + catch{console.log("report failed"); setTimeout(function() {try{document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} + catch{console.log("report failed2"); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}}, 800); } - },200); + }, 200); setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed"); - setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed2");}},1700)}},700) + setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed2");}}, 1700)}}, 700) } /*------------------------------------------------------------------------------ 4.7.24 SUBSCRIBE diff --git a/menu/skeleton-parts/general.js b/menu/skeleton-parts/general.js index 2d41a550a..4fdf67374 100644 --- a/menu/skeleton-parts/general.js +++ b/menu/skeleton-parts/general.js @@ -41,7 +41,7 @@ extension.skeleton.main.layers.section.general = { */ default_content_country: { component: 'select', text: 'defaultContentCountry', - options:[{text:"default",value:"default"},{text:"Afghanistan",value:"AF"},{text:"Albania",value:"AL"},{text:"Algeria",value:"DZ"},{text:"AmericanSamoa",value:"AS"},{text:"Andorra",value:"AD"},{text:"Angola",value:"AO"},{text:"Anguilla",value:"AI"},{text:"Antarctica",value:"AQ"},{text:"AntiguaandBarbuda",value:"AG"},{text:"Argentina",value:"AR"},{text:"Armenia",value:"AM"},{text:"Aruba",value:"AW"},{text:"Australia",value:"AU"},{text:"Austria",value:"AT"},{text:"Azerbaijan",value:"AZ"},{text:"Bahrain",value:"BH"},{text:"BailiwickofGuernsey",value:"GG"},{text:"Bangladesh",value:"BD"},{text:"Barbados",value:"BB"},{text:"Belarus",value:"BY"},{text:"Belgium",value:"BE"},{text:"Belize",value:"BZ"},{text:"Benin",value:"BJ"},{text:"Bermuda",value:"BM"},{text:"Bhutan",value:"BT"},{text:"Bolivia",value:"BO"},{text:"Bonaire",value:"BQ"},{text:"BosniaandHerzegovina",value:"BA"},{text:"Botswana",value:"BW"},{text:"BouvetIsland",value:"BV"},{text:"Brazil",value:"BR"},{text:"BritishIndianOceanTerritory",value:"IO"},{text:"BritishVirginIslands",value:"VG"},{text:"Brunei",value:"BN"},{text:"Bulgaria",value:"BG"},{text:"BurkinaFaso",value:"BF"},{text:"Burundi",value:"BI"},{text:"Cambodia",value:"KH"},{text:"Cameroon",value:"CM"},{text:"Canada",value:"CA"},{text:"CapeVerde",value:"CV"},{text:"CaymanIslands",value:"KY"},{text:"CentralAfricanRepublic",value:"CF"},{text:"Chad",value:"TD"},{text:"Chile",value:"CL"},{text:"China",value:"CN"},{text:"ChristmasIsland",value:"CX"},{text:"Cocos(Keeling)Islands",value:"CC"},{text:"CollectivityofSaintMartin",value:"MF"},{text:"Colombia",value:"CO"},{text:"Comoros",value:"KM"},{text:"CookIslands",value:"CK"},{text:"CostaRica",value:"CR"},{text:"Croatia",value:"HR"},{text:"Cuba",value:"CU"},{text:"Curaçao",value:"CW"},{text:"Cyprus",value:"CY"},{text:"CzechRepublic",value:"CZ"},{text:"DemocraticRepublicoftheCongo",value:"CD"},{text:"Denmark",value:"DK"},{text:"Djibouti",value:"DJ"},{text:"Dominica",value:"DM"},{text:"DominicanRepublic",value:"DO"},{text:"EastTimor",value:"TL"},{text:"Ecuador",value:"EC"},{text:"Egypt",value:"EG"},{text:"ElSalvador",value:"SV"},{text:"EquatorialGuinea",value:"GQ"},{text:"Eritrea",value:"ER"},{text:"Estonia",value:"EE"},{text:"Eswatini",value:"SZ"},{text:"Ethiopia",value:"ET"},{text:"FalklandIslands",value:"FK"},{text:"FaroeIslands",value:"FO"},{text:"FederatedStatesofMicronesia",value:"FM"},{text:"Fiji",value:"FJ"},{text:"Finland",value:"FI"},{text:"France",value:"FR"},{text:"FrenchGuiana",value:"GF"},{text:"FrenchPolynesia",value:"PF"},{text:"FrenchSouthernandAntarcticLands",value:"TF"},{text:"Gabon",value:"GA"},{text:"Georgia(country)",value:"GE"},{text:"Germany",value:"DE"},{text:"Ghana",value:"GH"},{text:"Gibraltar",value:"GI"},{text:"Greece",value:"GR"},{text:"Greenland",value:"GL"},{text:"Grenada",value:"GD"},{text:"Guadeloupe",value:"GP"},{text:"Guam",value:"GU"},{text:"Guatemala",value:"GT"},{text:"Guinea",value:"GN"},{text:"Guinea-Bissau",value:"GW"},{text:"Guyana",value:"GY"},{text:"Haiti",value:"HT"},{text:"HeardIslandandMcDonaldIslands",value:"HM"},{text:"HolySee",value:"VA"},{text:"Honduras",value:"HN"},{text:"HongKong",value:"HK"},{text:"Hungary",value:"HU"},{text:"Iceland",value:"IS"},{text:"India",value:"IN"},{text:"Indonesia",value:"ID"},{text:"Iran",value:"IR"},{text:"Iraq",value:"IQ"},{text:"IsleofMan",value:"IM"},{text:"Israel",value:"IL"},{text:"Italy",value:"IT"},{text:"IvoryCoast",value:"CI"},{text:"Jamaica",value:"JM"},{text:"Japan",value:"JP"},{text:"Jersey",value:"JE"},{text:"Jordan",value:"JO"},{text:"Kazakhstan",value:"KZ"},{text:"Kenya",value:"KE"},{text:"Kiribati",value:"KI"},{text:"Kuwait",value:"KW"},{text:"Kyrgyzstan",value:"KG"},{text:"Laos",value:"LA"},{text:"Latvia",value:"LV"},{text:"Lebanon",value:"LB"},{text:"Lesotho",value:"LS"},{text:"Liberia",value:"LR"},{text:"Libya",value:"LY"},{text:"Liechtenstein",value:"LI"},{text:"Lithuania",value:"LT"},{text:"Luxembourg",value:"LU"},{text:"Macau",value:"MO"},{text:"Madagascar",value:"MG"},{text:"Malawi",value:"MW"},{text:"Malaysia",value:"MY"},{text:"Maldives",value:"MV"},{text:"Mali",value:"ML"},{text:"Malta",value:"MT"},{text:"MarshallIslands",value:"MH"},{text:"Martinique",value:"MQ"},{text:"Mauritania",value:"MR"},{text:"Mauritius",value:"MU"},{text:"Mayotte",value:"YT"},{text:"Mexico",value:"MX"},{text:"Moldova",value:"MD"},{text:"Monaco",value:"MC"},{text:"Mongolia",value:"MN"},{text:"Montenegro",value:"ME"},{text:"Montserrat",value:"MS"},{text:"Morocco",value:"MA"},{text:"Mozambique",value:"MZ"},{text:"Myanmar",value:"MM"},{text:"Namibia",value:"NA"},{text:"Nauru",value:"NR"},{text:"Nepal",value:"NP"},{text:"Netherlands",value:"NL"},{text:"NewCaledonia",value:"NC"},{text:"NewZealand",value:"NZ"},{text:"Nicaragua",value:"NI"},{text:"Niger",value:"NE"},{text:"Nigeria",value:"NG"},{text:"Niue",value:"NU"},{text:"NorfolkIsland",value:"NF"},{text:"NorthKorea",value:"KP"},{text:"NorthMacedonia",value:"MK"},{text:"NorthernMarianaIslands",value:"MP"},{text:"Norway",value:"NO"},{text:"Oman",value:"OM"},{text:"Pakistan",value:"PK"},{text:"Palau",value:"PW"},{text:"Panama",value:"PA"},{text:"PapuaNewGuinea",value:"PG"},{text:"Paraguay",value:"PY"},{text:"Peru",value:"PE"},{text:"Philippines",value:"PH"},{text:"PitcairnIslands",value:"PN"},{text:"Poland",value:"PL"},{text:"Portugal",value:"PT"},{text:"PuertoRico",value:"PR"},{text:"Qatar",value:"QA"},{text:"RepublicofIreland",value:"IE"},{text:"RepublicoftheCongo",value:"CG"},{text:"Romania",value:"RO"},{text:"Russia",value:"RU"},{text:"Rwanda",value:"RW"},{text:"Réunion",value:"RE"},{text:"SaintBarthélemy",value:"BL"},{text:"SaintHelena",value:"SH"},{text:"SaintKittsandNevis",value:"KN"},{text:"SaintLucia",value:"LC"},{text:"SaintPierreandMiquelon",value:"PM"},{text:"SaintVincentandtheGrenadines",value:"VC"},{text:"Samoa",value:"WS"},{text:"SanMarino",value:"SM"},{text:"SaudiArabia",value:"SA"},{text:"Senegal",value:"SN"},{text:"Serbia",value:"RS"},{text:"Seychelles",value:"SC"},{text:"SierraLeone",value:"SL"},{text:"Singapore",value:"SG"},{text:"SintMaarten",value:"SX"},{text:"Slovakia",value:"SK"},{text:"Slovenia",value:"SI"},{text:"SolomonIslands",value:"SB"},{text:"Somalia",value:"SO"},{text:"SouthAfrica",value:"ZA"},{text:"SouthGeorgiaandtheSouthSandwichIslands",value:"GS"},{text:"SouthKorea",value:"KR"},{text:"SouthSudan",value:"SS"},{text:"Spain",value:"ES"},{text:"SriLanka",value:"LK"},{text:"StateofPalestine",value:"PS"},{text:"Sudan",value:"SD"},{text:"Suriname",value:"SR"},{text:"Svalbard",value:"SJ"},{text:"Sweden",value:"SE"},{text:"Switzerland",value:"CH"},{text:"Syria",value:"SY"},{text:"SãoToméandPríncipe",value:"ST"},{text:"Taiwan",value:"TW"},{text:"Tajikistan",value:"TJ"},{text:"Tanzania",value:"TZ"},{text:"Thailand",value:"TH"},{text:"TheBahamas",value:"BS"},{text:"TheGambia",value:"GM"},{text:"Togo",value:"TG"},{text:"Tokelau",value:"TK"},{text:"Tonga",value:"TO"},{text:"TrinidadandTobago",value:"TT"},{text:"Tunisia",value:"TN"},{text:"Turkey",value:"TR"},{text:"Turkmenistan",value:"TM"},{text:"TurksandCaicosIslands",value:"TC"},{text:"Tuvalu",value:"TV"},{text:"Uganda",value:"UG"},{text:"Ukraine",value:"UA"},{text:"UnitedArabEmirates",value:"AE"},{text:"UnitedKingdom",value:"GB"},{text:"UnitedStatesVirginIslands",value:"VI"},{text:"UnitedStates",value:"UM"},{text:"UnitedStates",value:"US"},{text:"Uruguay",value:"UY"},{text:"Uzbekistan",value:"UZ"},{text:"Vanuatu",value:"VU"},{text:"Venezuela",value:"VE"},{text:"Vietnam",value:"VN"},{text:"WallisandFutuna",value:"WF"},{text:"WesternSahara",value:"EH"},{text:"Yemen",value:"YE"},{text:"Zambia",value:"ZM"},{text:"Zimbabwe",value:"ZW"},{text:"ÅlandIslands",value:"AX"}] + options:[{text:"default", value:"default"}, {text:"Afghanistan", value:"AF"}, {text:"Albania", value:"AL"}, {text:"Algeria", value:"DZ"}, {text:"AmericanSamoa", value:"AS"}, {text:"Andorra", value:"AD"}, {text:"Angola", value:"AO"}, {text:"Anguilla", value:"AI"}, {text:"Antarctica", value:"AQ"}, {text:"AntiguaandBarbuda", value:"AG"}, {text:"Argentina", value:"AR"}, {text:"Armenia", value:"AM"}, {text:"Aruba", value:"AW"}, {text:"Australia", value:"AU"}, {text:"Austria", value:"AT"}, {text:"Azerbaijan", value:"AZ"}, {text:"Bahrain", value:"BH"}, {text:"BailiwickofGuernsey", value:"GG"}, {text:"Bangladesh", value:"BD"}, {text:"Barbados", value:"BB"}, {text:"Belarus", value:"BY"}, {text:"Belgium", value:"BE"}, {text:"Belize", value:"BZ"}, {text:"Benin", value:"BJ"}, {text:"Bermuda", value:"BM"}, {text:"Bhutan", value:"BT"}, {text:"Bolivia", value:"BO"}, {text:"Bonaire", value:"BQ"}, {text:"BosniaandHerzegovina", value:"BA"}, {text:"Botswana", value:"BW"}, {text:"BouvetIsland", value:"BV"}, {text:"Brazil", value:"BR"}, {text:"BritishIndianOceanTerritory", value:"IO"}, {text:"BritishVirginIslands", value:"VG"}, {text:"Brunei", value:"BN"}, {text:"Bulgaria", value:"BG"}, {text:"BurkinaFaso", value:"BF"}, {text:"Burundi", value:"BI"}, {text:"Cambodia", value:"KH"}, {text:"Cameroon", value:"CM"}, {text:"Canada", value:"CA"}, {text:"CapeVerde", value:"CV"}, {text:"CaymanIslands", value:"KY"}, {text:"CentralAfricanRepublic", value:"CF"}, {text:"Chad", value:"TD"}, {text:"Chile", value:"CL"}, {text:"China", value:"CN"}, {text:"ChristmasIsland", value:"CX"}, {text:"Cocos(Keeling)Islands", value:"CC"}, {text:"CollectivityofSaintMartin", value:"MF"}, {text:"Colombia", value:"CO"}, {text:"Comoros", value:"KM"}, {text:"CookIslands", value:"CK"}, {text:"CostaRica", value:"CR"}, {text:"Croatia", value:"HR"}, {text:"Cuba", value:"CU"}, {text:"Curaçao", value:"CW"}, {text:"Cyprus", value:"CY"}, {text:"CzechRepublic", value:"CZ"}, {text:"DemocraticRepublicoftheCongo", value:"CD"}, {text:"Denmark", value:"DK"}, {text:"Djibouti", value:"DJ"}, {text:"Dominica", value:"DM"}, {text:"DominicanRepublic", value:"DO"}, {text:"EastTimor", value:"TL"}, {text:"Ecuador", value:"EC"}, {text:"Egypt", value:"EG"}, {text:"ElSalvador", value:"SV"}, {text:"EquatorialGuinea", value:"GQ"}, {text:"Eritrea", value:"ER"}, {text:"Estonia", value:"EE"}, {text:"Eswatini", value:"SZ"}, {text:"Ethiopia", value:"ET"}, {text:"FalklandIslands", value:"FK"}, {text:"FaroeIslands", value:"FO"}, {text:"FederatedStatesofMicronesia", value:"FM"}, {text:"Fiji", value:"FJ"}, {text:"Finland", value:"FI"}, {text:"France", value:"FR"}, {text:"FrenchGuiana", value:"GF"}, {text:"FrenchPolynesia", value:"PF"}, {text:"FrenchSouthernandAntarcticLands", value:"TF"}, {text:"Gabon", value:"GA"}, {text:"Georgia(country)", value:"GE"}, {text:"Germany", value:"DE"}, {text:"Ghana", value:"GH"}, {text:"Gibraltar", value:"GI"}, {text:"Greece", value:"GR"}, {text:"Greenland", value:"GL"}, {text:"Grenada", value:"GD"}, {text:"Guadeloupe", value:"GP"}, {text:"Guam", value:"GU"}, {text:"Guatemala", value:"GT"}, {text:"Guinea", value:"GN"}, {text:"Guinea-Bissau", value:"GW"}, {text:"Guyana", value:"GY"}, {text:"Haiti", value:"HT"}, {text:"HeardIslandandMcDonaldIslands", value:"HM"}, {text:"HolySee", value:"VA"}, {text:"Honduras", value:"HN"}, {text:"HongKong", value:"HK"}, {text:"Hungary", value:"HU"}, {text:"Iceland", value:"IS"}, {text:"India", value:"IN"}, {text:"Indonesia", value:"ID"}, {text:"Iran", value:"IR"}, {text:"Iraq", value:"IQ"}, {text:"IsleofMan", value:"IM"}, {text:"Israel", value:"IL"}, {text:"Italy", value:"IT"}, {text:"IvoryCoast", value:"CI"}, {text:"Jamaica", value:"JM"}, {text:"Japan", value:"JP"}, {text:"Jersey", value:"JE"}, {text:"Jordan", value:"JO"}, {text:"Kazakhstan", value:"KZ"}, {text:"Kenya", value:"KE"}, {text:"Kiribati", value:"KI"}, {text:"Kuwait", value:"KW"}, {text:"Kyrgyzstan", value:"KG"}, {text:"Laos", value:"LA"}, {text:"Latvia", value:"LV"}, {text:"Lebanon", value:"LB"}, {text:"Lesotho", value:"LS"}, {text:"Liberia", value:"LR"}, {text:"Libya", value:"LY"}, {text:"Liechtenstein", value:"LI"}, {text:"Lithuania", value:"LT"}, {text:"Luxembourg", value:"LU"}, {text:"Macau", value:"MO"}, {text:"Madagascar", value:"MG"}, {text:"Malawi", value:"MW"}, {text:"Malaysia", value:"MY"}, {text:"Maldives", value:"MV"}, {text:"Mali", value:"ML"}, {text:"Malta", value:"MT"}, {text:"MarshallIslands", value:"MH"}, {text:"Martinique", value:"MQ"}, {text:"Mauritania", value:"MR"}, {text:"Mauritius", value:"MU"}, {text:"Mayotte", value:"YT"}, {text:"Mexico", value:"MX"}, {text:"Moldova", value:"MD"}, {text:"Monaco", value:"MC"}, {text:"Mongolia", value:"MN"}, {text:"Montenegro", value:"ME"}, {text:"Montserrat", value:"MS"}, {text:"Morocco", value:"MA"}, {text:"Mozambique", value:"MZ"}, {text:"Myanmar", value:"MM"}, {text:"Namibia", value:"NA"}, {text:"Nauru", value:"NR"}, {text:"Nepal", value:"NP"}, {text:"Netherlands", value:"NL"}, {text:"NewCaledonia", value:"NC"}, {text:"NewZealand", value:"NZ"}, {text:"Nicaragua", value:"NI"}, {text:"Niger", value:"NE"}, {text:"Nigeria", value:"NG"}, {text:"Niue", value:"NU"}, {text:"NorfolkIsland", value:"NF"}, {text:"NorthKorea", value:"KP"}, {text:"NorthMacedonia", value:"MK"}, {text:"NorthernMarianaIslands", value:"MP"}, {text:"Norway", value:"NO"}, {text:"Oman", value:"OM"}, {text:"Pakistan", value:"PK"}, {text:"Palau", value:"PW"}, {text:"Panama", value:"PA"}, {text:"PapuaNewGuinea", value:"PG"}, {text:"Paraguay", value:"PY"}, {text:"Peru", value:"PE"}, {text:"Philippines", value:"PH"}, {text:"PitcairnIslands", value:"PN"}, {text:"Poland", value:"PL"}, {text:"Portugal", value:"PT"}, {text:"PuertoRico", value:"PR"}, {text:"Qatar", value:"QA"}, {text:"RepublicofIreland", value:"IE"}, {text:"RepublicoftheCongo", value:"CG"}, {text:"Romania", value:"RO"}, {text:"Russia", value:"RU"}, {text:"Rwanda", value:"RW"}, {text:"Réunion", value:"RE"}, {text:"SaintBarthélemy", value:"BL"}, {text:"SaintHelena", value:"SH"}, {text:"SaintKittsandNevis", value:"KN"}, {text:"SaintLucia", value:"LC"}, {text:"SaintPierreandMiquelon", value:"PM"}, {text:"SaintVincentandtheGrenadines", value:"VC"}, {text:"Samoa", value:"WS"}, {text:"SanMarino", value:"SM"}, {text:"SaudiArabia", value:"SA"}, {text:"Senegal", value:"SN"}, {text:"Serbia", value:"RS"}, {text:"Seychelles", value:"SC"}, {text:"SierraLeone", value:"SL"}, {text:"Singapore", value:"SG"}, {text:"SintMaarten", value:"SX"}, {text:"Slovakia", value:"SK"}, {text:"Slovenia", value:"SI"}, {text:"SolomonIslands", value:"SB"}, {text:"Somalia", value:"SO"}, {text:"SouthAfrica", value:"ZA"}, {text:"SouthGeorgiaandtheSouthSandwichIslands", value:"GS"}, {text:"SouthKorea", value:"KR"}, {text:"SouthSudan", value:"SS"}, {text:"Spain", value:"ES"}, {text:"SriLanka", value:"LK"}, {text:"StateofPalestine", value:"PS"}, {text:"Sudan", value:"SD"}, {text:"Suriname", value:"SR"}, {text:"Svalbard", value:"SJ"}, {text:"Sweden", value:"SE"}, {text:"Switzerland", value:"CH"}, {text:"Syria", value:"SY"}, {text:"SãoToméandPríncipe", value:"ST"}, {text:"Taiwan", value:"TW"}, {text:"Tajikistan", value:"TJ"}, {text:"Tanzania", value:"TZ"}, {text:"Thailand", value:"TH"}, {text:"TheBahamas", value:"BS"}, {text:"TheGambia", value:"GM"}, {text:"Togo", value:"TG"}, {text:"Tokelau", value:"TK"}, {text:"Tonga", value:"TO"}, {text:"TrinidadandTobago", value:"TT"}, {text:"Tunisia", value:"TN"}, {text:"Turkey", value:"TR"}, {text:"Turkmenistan", value:"TM"}, {text:"TurksandCaicosIslands", value:"TC"}, {text:"Tuvalu", value:"TV"}, {text:"Uganda", value:"UG"}, {text:"Ukraine", value:"UA"}, {text:"UnitedArabEmirates", value:"AE"}, {text:"UnitedKingdom", value:"GB"}, {text:"UnitedStatesVirginIslands", value:"VI"}, {text:"UnitedStates", value:"UM"}, {text:"UnitedStates", value:"US"}, {text:"Uruguay", value:"UY"}, {text:"Uzbekistan", value:"UZ"}, {text:"Vanuatu", value:"VU"}, {text:"Venezuela", value:"VE"}, {text:"Vietnam", value:"VN"}, {text:"WallisandFutuna", value:"WF"}, {text:"WesternSahara", value:"EH"}, {text:"Yemen", value:"YE"}, {text:"Zambia", value:"ZM"}, {text:"Zimbabwe", value:"ZW"}, {text:"ÅlandIslands", value:"AX"}] }, cursorLighting: { component: 'switch', @@ -220,7 +220,7 @@ extension.skeleton.main.layers.section.general = { }], tags: 'preview quality' } - },section_2: { + }, section_2: { component: 'section', variant: 'card', title: 'watchedVideos', @@ -235,7 +235,7 @@ extension.skeleton.main.layers.section.general = { this.nextSibling.click(); } } - } , 250); } + }, 250); } } }, track_watched_videos: { From 27535effa1416c417b43f5c07a922178c399fd61 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 23:26:50 +0800 Subject: [PATCH 13/17] Add eslint-plugin-compat --- eslint.config.mjs | 8 +- package-lock.json | 214 +++++++++++++++++++++++++++++----------------- package.json | 10 ++- 3 files changed, 152 insertions(+), 80 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index 5f7f919d5..7cdcd190f 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -3,6 +3,8 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import js from "@eslint/js"; import { FlatCompat } from "@eslint/eslintrc"; +import { fixupConfigRules } from '@eslint/compat' +import eslintPluginCompat from 'eslint-plugin-compat' const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -12,7 +14,11 @@ const compat = new FlatCompat({ allConfig: js.configs.all }); -export default [...compat.extends("eslint:recommended"), { +const compatConfiguration = fixupConfigRules( + eslintPluginCompat.configs['flat/recommended'], +) + +export default [...compat.extends("eslint:recommended"), ...compatConfiguration, { ignores: ["*.mjs"], languageOptions: { globals: { diff --git a/package-lock.json b/package-lock.json index 27dae9eaa..b183c3f50 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,9 @@ "version": "1.0.0", "license": "ISC", "dependencies": { - "@eslint/migrate-config": "^1.1.1" + "@eslint/compat": "^1.1.0", + "@eslint/migrate-config": "^1.1.1", + "eslint-plugin-compat": "^5.0.0" }, "devDependencies": { "@eslint/eslintrc": "latest", @@ -603,7 +605,6 @@ "version": "4.4.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", "integrity": "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==", - "dev": true, "license": "MIT", "dependencies": { "eslint-visitor-keys": "^3.3.0" @@ -619,7 +620,6 @@ "version": "3.4.3", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, "license": "Apache-2.0", "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -632,7 +632,6 @@ "version": "4.11.0", "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.11.0.tgz", "integrity": "sha512-G/M/tIiMrTAxEWRfLfQJMmGNX28IxBg4PBz8XqQhqUHLFI6TL2htpIB1iQCj144V5ee/JaKyT9/WZ0MGZWfA7A==", - "dev": true, "license": "MIT", "engines": { "node": "^12.0.0 || ^14.0.0 || >=16.0.0" @@ -651,7 +650,6 @@ "version": "0.17.0", "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.17.0.tgz", "integrity": "sha512-A68TBu6/1mHHuc5YJL0U0VVeGNiklLAL6rRmhTCP2B5XjWLMnrX+HkO+IAXyHvks5cyyY1jjK5ITPQ1HGS2EVA==", - "dev": true, "license": "Apache-2.0", "dependencies": { "@eslint/object-schema": "^2.1.4", @@ -719,7 +717,6 @@ "version": "9.6.0", "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.6.0.tgz", "integrity": "sha512-D9B0/3vNg44ZeWbYMpBoXqNP4j6eQD5vNwIlGAuFRRzK/WtT/jvDQW3Bi9kkf3PMDMlM7Yi+73VLUsn5bJcl8A==", - "dev": true, "license": "MIT", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -759,7 +756,6 @@ "version": "2.1.4", "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.4.tgz", "integrity": "sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==", - "dev": true, "license": "Apache-2.0", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -769,7 +765,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, "license": "Apache-2.0", "engines": { "node": ">=12.22" @@ -783,7 +778,6 @@ "version": "0.3.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.0.tgz", "integrity": "sha512-d2CGZR2o7fS6sWB7DG/3a95bGKQyHMACZ5aW8qGkkqQpUoZV6C0X7Pc7l4ZNMZkfNBf4VWNe9E1jRsf0G146Ew==", - "dev": true, "license": "Apache-2.0", "engines": { "node": ">=18.18" @@ -1144,11 +1138,16 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@mdn/browser-compat-data": { + "version": "5.5.36", + "resolved": "https://registry.npmjs.org/@mdn/browser-compat-data/-/browser-compat-data-5.5.36.tgz", + "integrity": "sha512-iPM4MKJaztppo2RlbZuPaneX/I09grYl4fCGG9hQ6gLAIcfrihdOAYmKFnlRG9krVJOUogbeMFBhh9vrN7CZqw==", + "license": "CC0-1.0" + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, "license": "MIT", "dependencies": { "@nodelib/fs.stat": "2.0.5", @@ -1162,7 +1161,6 @@ "version": "2.0.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, "license": "MIT", "engines": { "node": ">= 8" @@ -1172,7 +1170,6 @@ "version": "1.2.8", "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, "license": "MIT", "dependencies": { "@nodelib/fs.scandir": "2.1.5", @@ -1372,7 +1369,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, "engines": { "node": ">=8" } @@ -1381,7 +1377,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, "dependencies": { "color-convert": "^2.0.1" }, @@ -1414,6 +1409,15 @@ "sprintf-js": "~1.0.2" } }, + "node_modules/ast-metadata-inferer": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/ast-metadata-inferer/-/ast-metadata-inferer-0.8.0.tgz", + "integrity": "sha512-jOMKcHht9LxYIEQu+RVd22vtgrPaVCtDRQ/16IGmurdzxvYbDd5ynxjnyrzLnieG96eTcAyaoj/wN/4/1FyyeA==", + "license": "MIT", + "dependencies": { + "@mdn/browser-compat-data": "^5.2.34" + } + }, "node_modules/ast-types": { "version": "0.16.1", "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.16.1.tgz", @@ -1563,7 +1567,6 @@ "version": "4.23.0", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz", "integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==", - "dev": true, "funding": [ { "type": "opencollective", @@ -1633,7 +1636,6 @@ "version": "1.0.30001629", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001629.tgz", "integrity": "sha512-c3dl911slnQhmxUIT4HhYzT7wnBK/XYpGnYLOj4nJBaRiw52Ibe7YxlDaAeRECvA786zCuExhxIUJ2K7nHMrBw==", - "dev": true, "funding": [ { "type": "opencollective", @@ -1653,7 +1655,6 @@ "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -1729,7 +1730,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, "dependencies": { "color-name": "~1.1.4" }, @@ -1740,8 +1740,7 @@ "node_modules/color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, "node_modules/concat-map": { "version": "0.0.1", @@ -1785,7 +1784,6 @@ "version": "7.0.3", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", - "dev": true, "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -1829,7 +1827,6 @@ "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true, "license": "MIT" }, "node_modules/deepmerge": { @@ -1862,8 +1859,7 @@ "node_modules/electron-to-chromium": { "version": "1.4.794", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.794.tgz", - "integrity": "sha512-6FApLtsYhDCY0Vglq3AptsdxQ+PJLc6AxlAM0HjEihUAiOPPbkASEsq9gtxUeZY9o0sJIEa3WnF0vVH4VT4iug==", - "dev": true + "integrity": "sha512-6FApLtsYhDCY0Vglq3AptsdxQ+PJLc6AxlAM0HjEihUAiOPPbkASEsq9gtxUeZY9o0sJIEa3WnF0vVH4VT4iug==" }, "node_modules/emittery": { "version": "0.13.1", @@ -1896,7 +1892,6 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", - "dev": true, "engines": { "node": ">=6" } @@ -1914,7 +1909,6 @@ "version": "9.6.0", "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.6.0.tgz", "integrity": "sha512-ElQkdLMEEqQNM9Njff+2Y4q2afHk7JpkPvrd7Xh7xefwgQynqPxwf55J7di9+MEibWUGdNjFF9ITG9Pck5M84w==", - "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", @@ -1962,11 +1956,117 @@ "url": "https://eslint.org/donate" } }, + "node_modules/eslint-plugin-compat": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-compat/-/eslint-plugin-compat-5.0.0.tgz", + "integrity": "sha512-29KNWyFkUbNVf6TIKVe9SVCGCtHjML3HnUg9C8LG2GsXf7miAeBOgdMc1n2B5n0sHUzg1/A4IFly7Jyf1gSbgQ==", + "license": "MIT", + "dependencies": { + "@mdn/browser-compat-data": "^5.5.19", + "ast-metadata-inferer": "^0.8.0", + "browserslist": "^4.23.0", + "caniuse-lite": "^1.0.30001605", + "find-up": "^5.0.0", + "globals": "^13.24.0", + "lodash.memoize": "^4.1.2", + "semver": "^7.6.0" + }, + "engines": { + "node": ">=14.x" + }, + "peerDependencies": { + "eslint": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/eslint-plugin-compat/node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint-plugin-compat/node_modules/globals": { + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint-plugin-compat/node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint-plugin-compat/node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint-plugin-compat/node_modules/semver": { + "version": "7.6.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", + "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/eslint-plugin-compat/node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/eslint-scope": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.0.1.tgz", "integrity": "sha512-pL8XjgP4ZOmmwfFE8mEhSxA7ZY4C+LWyqjQ3o4yWkkmD0qcMT9kkW3zWHOczhWcjTSgqycYAgwSlXvZltv65og==", - "dev": true, "license": "BSD-2-Clause", "dependencies": { "esrecurse": "^4.3.0", @@ -1995,7 +2095,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, "license": "MIT", "engines": { "node": ">=10" @@ -2008,7 +2107,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, "license": "MIT", "dependencies": { "locate-path": "^6.0.0", @@ -2025,7 +2123,6 @@ "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, "license": "MIT", "dependencies": { "p-locate": "^5.0.0" @@ -2041,7 +2138,6 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, "license": "MIT", "dependencies": { "p-limit": "^3.0.2" @@ -2086,7 +2182,6 @@ "version": "1.5.0", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", - "dev": true, "license": "BSD-3-Clause", "dependencies": { "estraverse": "^5.1.0" @@ -2099,7 +2194,6 @@ "version": "4.3.0", "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, "license": "BSD-2-Clause", "dependencies": { "estraverse": "^5.2.0" @@ -2112,7 +2206,6 @@ "version": "5.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, "license": "BSD-2-Clause", "engines": { "node": ">=4.0" @@ -2122,7 +2215,6 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, "license": "BSD-2-Clause", "engines": { "node": ">=0.10.0" @@ -2191,14 +2283,12 @@ "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true, "license": "MIT" }, "node_modules/fastq": { "version": "1.17.1", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", - "dev": true, "license": "ISC", "dependencies": { "reusify": "^1.0.4" @@ -2217,7 +2307,6 @@ "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", - "dev": true, "license": "MIT", "dependencies": { "flat-cache": "^4.0.0" @@ -2255,7 +2344,6 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", - "dev": true, "license": "MIT", "dependencies": { "flatted": "^3.2.9", @@ -2269,7 +2357,6 @@ "version": "3.3.1", "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.1.tgz", "integrity": "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw==", - "dev": true, "license": "ISC" }, "node_modules/fs.realpath": { @@ -2365,7 +2452,6 @@ "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, "license": "ISC", "dependencies": { "is-glob": "^4.0.3" @@ -2397,7 +2483,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, "engines": { "node": ">=8" } @@ -2486,7 +2571,6 @@ "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, "engines": { "node": ">=0.8.19" } @@ -2530,7 +2614,6 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -2558,7 +2641,6 @@ "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, "license": "MIT", "dependencies": { "is-extglob": "^2.1.1" @@ -2580,7 +2662,6 @@ "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -2607,8 +2688,7 @@ "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" }, "node_modules/istanbul-lib-coverage": { "version": "3.2.2", @@ -3329,7 +3409,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true, "license": "MIT" }, "node_modules/json-parse-even-better-errors": { @@ -3348,7 +3427,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true, "license": "MIT" }, "node_modules/json5": { @@ -3367,7 +3445,6 @@ "version": "4.5.4", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", - "dev": true, "license": "MIT", "dependencies": { "json-buffer": "3.0.1" @@ -3395,7 +3472,6 @@ "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, "license": "MIT", "dependencies": { "prelude-ls": "^1.2.1", @@ -3423,11 +3499,16 @@ "node": ">=8" } }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true, "license": "MIT" }, "node_modules/lru-cache": { @@ -3522,8 +3603,7 @@ "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==" }, "node_modules/node-int64": { "version": "0.4.0", @@ -3534,8 +3614,7 @@ "node_modules/node-releases": { "version": "2.0.14", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", - "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", - "dev": true + "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==" }, "node_modules/nopt": { "version": "4.0.3", @@ -3599,7 +3678,6 @@ "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", - "dev": true, "license": "MIT", "dependencies": { "deep-is": "^0.1.3", @@ -3646,7 +3724,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, "dependencies": { "yocto-queue": "^0.1.0" }, @@ -3727,7 +3804,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, "engines": { "node": ">=8" } @@ -3745,7 +3821,6 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, "engines": { "node": ">=8" } @@ -3759,8 +3834,7 @@ "node_modules/picocolors": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", - "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", - "dev": true + "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==" }, "node_modules/picomatch": { "version": "2.3.1", @@ -3799,7 +3873,6 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.8.0" @@ -3879,7 +3952,6 @@ "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, "funding": [ { "type": "github", @@ -3993,7 +4065,6 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", - "dev": true, "license": "MIT", "engines": { "iojs": ">=1.0.0", @@ -4004,7 +4075,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, "funding": [ { "type": "github", @@ -4037,7 +4107,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, "dependencies": { "shebang-regex": "^3.0.0" }, @@ -4049,7 +4118,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, "engines": { "node": ">=8" } @@ -4148,7 +4216,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -4189,7 +4256,6 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -4227,7 +4293,6 @@ "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true, "license": "MIT" }, "node_modules/tiny-invariant": { @@ -4273,7 +4338,6 @@ "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, "license": "MIT", "dependencies": { "prelude-ls": "^1.2.1" @@ -4313,7 +4377,6 @@ "version": "1.0.16", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.16.tgz", "integrity": "sha512-KVbTxlBYlckhF5wgfyZXTWnMn7MMZjMu9XG8bPlliUOP9ThaF4QnhP8qrjrH7DRzHfSk0oQv1wToW+iA5GajEQ==", - "dev": true, "funding": [ { "type": "opencollective", @@ -4381,7 +4444,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "dependencies": { "isexe": "^2.0.0" }, @@ -4396,7 +4458,6 @@ "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -4484,7 +4545,6 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, "engines": { "node": ">=10" }, diff --git a/package.json b/package.json index a55503c5b..202a25153 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,12 @@ "jslint": "^0.12.1" }, "dependencies": { - "@eslint/migrate-config": "^1.1.1" - } + "@eslint/compat": "^1.1.0", + "@eslint/migrate-config": "^1.1.1", + "eslint-plugin-compat": "^5.0.0" + }, + "browserslist": [ + "last 10 versions, not dead, > 1%", + "not op_mini all" + ] } From 34aaea37bd71cfce822a5a4c8c989184f89d67cc Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 23:29:50 +0800 Subject: [PATCH 14/17] Add space-before-function-paren and keyword-spacing --- background.js | 18 +- eslint.config.mjs | 2 + js&css/extension/init.js | 6 +- .../www.youtube.com/general/general.js | 8 +- js&css/web-accessible/core.js | 10 +- js&css/web-accessible/functions.js | 34 +- js&css/web-accessible/init.js | 6 +- .../www.youtube.com/appearance.js | 54 +-- .../www.youtube.com/blocklist.js | 4 +- .../web-accessible/www.youtube.com/channel.js | 12 +- .../web-accessible/www.youtube.com/player.js | 42 +- .../www.youtube.com/playlist.js | 2 +- .../www.youtube.com/settings.js | 6 +- .../www.youtube.com/shortcuts.js | 36 +- .../web-accessible/www.youtube.com/themes.js | 2 +- menu/satus.js | 392 +++++++++--------- menu/skeleton-parts/dark-light-switch.js | 8 +- menu/skeleton-parts/search.js | 2 +- 18 files changed, 323 insertions(+), 321 deletions(-) diff --git a/background.js b/background.js index 0a042f68c..7359ae5de 100644 --- a/background.js +++ b/background.js @@ -27,7 +27,7 @@ # IMPORTING OLD SETTINGS -----------------------------*/ chrome.runtime.onInstalled.addListener(function (installed) { - if(installed.reason == 'update') { + if (installed.reason == 'update') { // var thisVersion = chrome.runtime.getManifest().version; // console.log("Updated from " + installed.previousVersion + " to " + thisVersion + "!"); // Shortcut renames: @@ -93,10 +93,10 @@ chrome.runtime.onInstalled.addListener(function (installed) { }); } }); - } else if(installed.reason == 'install') { - if(navigator.userAgent.indexOf("Firefox") != -1){ + } else if (installed.reason == 'install') { + if (navigator.userAgent.indexOf("Firefox") != -1){ chrome.storage.local.set({below_player_pip: false})} - if(navigator.userAgent.indexOf('Safari') !== -1 + if (navigator.userAgent.indexOf('Safari') !== -1 && (!/Windows|Chrom/.test(navigator.userAgent) || /Macintosh|iPhone/.test(navigator.userAgent))) { chrome.storage.local.set({below_player_pip: false}) @@ -108,7 +108,7 @@ chrome.runtime.onInstalled.addListener(function (installed) { /*-------------------------------------------------------------- # LOCALE --------------------------------------------------------------*/ -function getLocale(language, callback) { +function getLocale (language, callback) { language = language.replace('-', '_'); fetch('_locales/' + language.substring(0, 2) + '/messages.json').then(function (response) { if (response.ok) { @@ -130,7 +130,7 @@ function getLocale(language, callback) { /*-------------------------------------------------------------- # CONTEXT MENU --------------------------------------------------------------*/ -function updateContextMenu(language) { +function updateContextMenu (language) { if (!language) { language = chrome.i18n.getUILanguage(); } @@ -188,7 +188,7 @@ chrome.storage.onChanged.addListener(function (changes) { --------------------------------------------------------------*/ let tabConnected = {}; -function tabPrune(callback) { +function tabPrune (callback) { chrome.tabs.query({ url: 'https://www.youtube.com/*' }).then(function (tabs) { let tabIds = []; for (let tab of tabs) { @@ -252,7 +252,7 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { //console.log(message); //console.log(sender); - switch(message.action || message.name || message) { + switch (message.action || message.name || message) { case 'play': tabPrune(function () { for (let id in tabConnected) { @@ -297,7 +297,7 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { chrome.windows.create(data, pw => {}); //append to title? - chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) { + chrome.tabs.onUpdated.addListener(function listener (tabId, changeInfo) { if (tabId === tID && changeInfo.status === 'complete' && !message.title.startsWith("undefined")) { chrome.tabs.onUpdated.removeListener(listener); chrome.scripting.executeScript({ target: { tabId: tID }, func: () => { document.title = `${message.title} - ImprovedTube`; } }); //manifest3 diff --git a/eslint.config.mjs b/eslint.config.mjs index 7cdcd190f..330f2c895 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -47,6 +47,8 @@ export default [...compat.extends("eslint:recommended"), ...compatConfiguration, "no-fallthrough": ["error", { "allowEmptyCase": true }], "no-implicit-globals": "error", "no-multiple-empty-lines": ["error", {"max": 1, "maxBOF": 0, "maxEOF": 0}], + "keyword-spacing": ["warn", { "before": true, "after": true }], + "space-before-function-paren": "warn", "max-len": ["error", { code: 255, ignoreUrls: true, diff --git a/js&css/extension/init.js b/js&css/extension/init.js index 78e7308e8..6ce852cbf 100644 --- a/js&css/extension/init.js +++ b/js&css/extension/init.js @@ -24,7 +24,7 @@ extension.events.on('init', function (resolve) { async: true }); -function bodyReady() { +function bodyReady () { if (extension.ready && extension.domReady) { extension.features.addScrollToTop(); extension.features.font(); @@ -179,7 +179,7 @@ document.addEventListener('it-message-from-youtube', function () { extension.storage.data.blocklist = {videos: {}, channels: {}}; } - switch(message.type) { + switch (message.type) { case 'channel': if (!extension.storage.data.blocklist.channels || typeof extension.storage.data.blocklist.channels !== 'object') { extension.storage.data.blocklist.channels = {}; @@ -244,5 +244,5 @@ document.addEventListener('it-message-from-youtube', function () { document.addEventListener('it-play', function (event) { var videos = document.querySelectorAll('video'); try {chrome.runtime.sendMessage({action: 'play'})} - catch(error){console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } + catch (error){console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } }); diff --git a/js&css/extension/www.youtube.com/general/general.js b/js&css/extension/www.youtube.com/general/general.js index f93509cb4..634bcd137 100644 --- a/js&css/extension/www.youtube.com/general/general.js +++ b/js&css/extension/www.youtube.com/general/general.js @@ -249,7 +249,7 @@ extension.features.popupWindowButtons = function (event) { target.itPopupWindowButton.addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); - try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch(error) { console.log(error)}; + try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch (error) { console.log(error)}; ytPlayer = document.querySelector("#movie_player"); if (ytPlayer){width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} else { width = innerWidth * 0.4; height = innerHeight * 0.4; } @@ -444,7 +444,7 @@ extension.features.trackWatchedVideos = function () { extension.features.thumbnailsQuality = function (anything) { var option = extension.storage.get('thumbnails_quality'); - function handler(thumbnail) { + function handler (thumbnail) { if (!thumbnail.dataset.defaultSrc && extension.features.thumbnailsQuality.regex.test(thumbnail.src)) { thumbnail.dataset.defaultSrc = thumbnail.src; @@ -553,7 +553,7 @@ extension.features.openNewTab = function (){ inputField.addEventListener("input", () => searchedAlready = false); - function applySuggestionListeners() { + function applySuggestionListeners () { const suggestionContainers = document.querySelectorAll("div[class^='sbqs'], div[class^='sbpqs']"); suggestionContainers.forEach((suggestionsContainer) => { suggestionsContainer.addEventListener("mousedown", (event) => { @@ -567,7 +567,7 @@ extension.features.openNewTab = function (){ }); } - function performSearchNewTab(query) { + function performSearchNewTab (query) { inputField.value = ""; inputField.focus(); const newTabURL = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`; diff --git a/js&css/web-accessible/core.js b/js&css/web-accessible/core.js index ea4aa724e..47d95bf36 100644 --- a/js&css/web-accessible/core.js +++ b/js&css/web-accessible/core.js @@ -99,7 +99,7 @@ CODEC || 30FPS file to patch HTMLMediaElement before YT player uses it. --------------------------------------------------------------*/ if (localStorage['it-codec'] || localStorage['it-player30fps']) { - function overwrite(self, callback, mime) { + function overwrite (self, callback, mime) { if (localStorage['it-codec']) { var re = new RegExp(localStorage['it-codec']); // /webm|vp8|vp9|av01/ @@ -220,7 +220,7 @@ document.addEventListener('it-message-from-extension', function () { } } - switch(camelized_key) { + switch (camelized_key) { case 'blocklist': case 'blocklistActivate': ImprovedTube.blocklistInit(); @@ -246,9 +246,9 @@ document.addEventListener('it-message-from-extension', function () { case 'description': if (ImprovedTube.storage.description === "expanded" || ImprovedTube.storage.description === "classic_expanded") { - try{document.querySelector("#more").click() || document.querySelector("#expand").click();} catch{} + try {document.querySelector("#more").click() || document.querySelector("#expand").click();} catch {} } else if (ImprovedTube.storage.description === "normal" || ImprovedTube.storage.description === "classic") { - try{document.querySelector("#less").click() || document.querySelector("#collapse").click();} catch{} + try {document.querySelector("#less").click() || document.querySelector("#collapse").click();} catch {} } break @@ -404,7 +404,7 @@ document.addEventListener('it-message-from-extension', function () { if (message.key.startsWith('shortcut_')) camelized_key = 'shortcuts'; if (ImprovedTube[camelized_key]) { - try{ImprovedTube[camelized_key]()}catch{}; + try {ImprovedTube[camelized_key]()} catch {}; } } else if (message.focus === true && ImprovedTube.elements.player) { ImprovedTube.focus = true; diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index 4b3186398..b5d276967 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -56,11 +56,11 @@ ImprovedTube.ytElementsHandler = function (node) { if (index === 0) { if (this.storage.playlist_reverse === true) { //can be precise: - try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode;} - catch{try{this.elements.playlist.actions = node;}catch{}} + try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode;} + catch {try {this.elements.playlist.actions = node;} catch {}} } } } @@ -73,11 +73,11 @@ ImprovedTube.ytElementsHandler = function (node) { if (this.storage.playlist_reverse === true) { //can be precise: - try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode.parentNode;} - catch{try{this.elements.playlist.actions = node.parentNode;} - catch{try{this.elements.playlist.actions = node;}catch{}} + try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode;} + catch {try {this.elements.playlist.actions = node;} catch {}} } } } @@ -360,10 +360,10 @@ ImprovedTube.initPlayer = function () { var timeUpdateInterval = null; var noTimeUpdate = null; -ImprovedTube.playerOnTimeUpdate = function() { +ImprovedTube.playerOnTimeUpdate = function () { var currentTime = Date.now(); if (!timeUpdateInterval) { - timeUpdateInterval = setInterval(function() { + timeUpdateInterval = setInterval(function () { if (ImprovedTube.video_src !== this.src) { ImprovedTube.video_src = this.src; @@ -382,7 +382,7 @@ ImprovedTube.playerOnTimeUpdate = function() { }, 500); } clearInterval(noTimeUpdate); - noTimeUpdate = setTimeout(function() { + noTimeUpdate = setTimeout(function () { clearInterval(timeUpdateInterval); timeUpdateInterval = null; }, 987); @@ -431,7 +431,7 @@ ImprovedTube.onkeydown = function () { ImprovedTube.onmousedown = function () { window.addEventListener('mousedown', function (event) { if (!ImprovedTube.user_interacted) { - setTimeout(function(){ImprovedTube.user_interacted = true}, 3000); + setTimeout(function (){ImprovedTube.user_interacted = true}, 3000); if (ImprovedTube.elements.player && ImprovedTube.elements.player.classList.contains('ad-showing') === false) { var path = event.composedPath(); for (var i = 0, l = path.length; i < l; i++) { @@ -533,8 +533,8 @@ ImprovedTube.createIconButton = function (options) { path = document.createElementNS('http://www.w3.org/2000/svg', 'path'), type = this.button_icons[options.type]; - for(const attr of type.svg) svg.setAttribute(attr[0], attr[1]); - for(const attr of type.path) path.setAttribute(attr[0], attr[1]); + for (const attr of type.svg) svg.setAttribute(attr[0], attr[1]); + for (const attr of type.path) path.setAttribute(attr[0], attr[1]); svg.appendChild(path); button.appendChild(svg); @@ -579,7 +579,7 @@ ImprovedTube.createPlayerButton = function (options) { tooltip.textContent = this.dataset.title; if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)){ tooltip.style.zIndex = 10001;} // needed for cinema mode - function mouseleave() { + function mouseleave () { tooltip.remove(); this.removeEventListener('mouseleave', mouseleave); diff --git a/js&css/web-accessible/init.js b/js&css/web-accessible/init.js index 2bd172ed4..3fd9da296 100644 --- a/js&css/web-accessible/init.js +++ b/js&css/web-accessible/init.js @@ -16,7 +16,7 @@ ImprovedTube.observer = new MutationObserver(function (mutationList) { } for (const node of mutation.removedNodes){ - if(node.nodeName === 'BUTTON' && node.id === 'it-popup-playlist-button') ImprovedTube.playlistPopupUpdate(); + if (node.nodeName === 'BUTTON' && node.id === 'it-popup-playlist-button') ImprovedTube.playlistPopupUpdate(); } } if (mutation.target && mutation.target.id === 'owner-sub-count') { @@ -105,8 +105,8 @@ ImprovedTube.init = function () { this.onmousedown(); this.youtubeLanguage(); this.myColors(); - if(this.storage.undo_the_new_sidebar === true){this.undoTheNewSidebar();} - if(this.storage.description === "sidebar"){this.descriptionSidebar();} + if (this.storage.undo_the_new_sidebar === true){this.undoTheNewSidebar();} + if (this.storage.description === "sidebar"){this.descriptionSidebar();} this.channelCompactTheme(); if (ImprovedTube.elements.player && ImprovedTube.elements.player.setPlaybackRate) { diff --git a/js&css/web-accessible/www.youtube.com/appearance.js b/js&css/web-accessible/www.youtube.com/appearance.js index ee1fb8d0b..857c37e4f 100644 --- a/js&css/web-accessible/www.youtube.com/appearance.js +++ b/js&css/web-accessible/www.youtube.com/appearance.js @@ -150,10 +150,10 @@ ImprovedTube.playerRemainingDuration = function () { /*------------------------------------------------------------------------------ Comments Sidebar Simple ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebarSimple = function() { if(ImprovedTube.storage.comments_sidebar_simple === true){ - if(window.matchMedia("(min-width: 1599px)").matches) { +ImprovedTube.commentsSidebarSimple = function () { if (ImprovedTube.storage.comments_sidebar_simple === true){ + if (window.matchMedia("(min-width: 1599px)").matches) { document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments"));} - if(window.matchMedia("(max-width: 1598px)").matches) { + if (window.matchMedia("(max-width: 1598px)").matches) { document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); setTimeout(function () { document.querySelector("#primary-inner").appendChild(document.querySelector("#related"));} @@ -163,10 +163,10 @@ ImprovedTube.commentsSidebarSimple = function() { if(ImprovedTube.storage.commen /*------------------------------------------------------------------------------ Comments Sidebar ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sidebar === true){ +ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_sidebar === true){ const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); let hasApplied = 0; - if(/watch\?/.test(location.href)) { + if (/watch\?/.test(location.href)) { sidebar(); styleScrollbars(); setGrid(); @@ -174,9 +174,9 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid window.addEventListener("resize", sidebar) } - function sidebar(){ + function sidebar (){ resizePlayer(); - if(window.matchMedia("(min-width: 1952px)").matches) { + if (window.matchMedia("(min-width: 1952px)").matches) { if (!hasApplied) { initialSetup() @@ -187,7 +187,7 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid } hasApplied = 1 } - else if(window.matchMedia("(min-width: 1000px)").matches) { + else if (window.matchMedia("(min-width: 1000px)").matches) { if (!hasApplied) { initialSetup(); } @@ -197,7 +197,7 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid hasApplied = 2 } else { /// <1000 - if(hasApplied == 1){ + if (hasApplied == 1){ document.getElementById("primary-inner").appendChild(document.getElementById("related")); let comments = document.querySelector("#comments"); let below = document.getElementById("below"); @@ -211,7 +211,7 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid hasApplied = 0; } } - function setGrid(){ + function setGrid (){ let checkParentInterval = setInterval(() => { container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; if (container) { @@ -222,7 +222,7 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid } }, 250); } - function initialSetup() { + function initialSetup () { let secondaryInner = document.getElementById("secondary-inner"); let primaryInner = document.getElementById("primary-inner"); let comments = document.querySelector("#comments"); @@ -233,20 +233,20 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid secondaryInner.appendChild(comments); }) } - function resizePlayer() { + function resizePlayer () { const width = video.offsetWidth + 24; const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); document.getElementById("primary").style.width = `${width}px`; player.style.width = `${width}px`; } - function styleScrollbars(){ + function styleScrollbars (){ if (!navigator.userAgent.toLowerCase().includes("mac")){ let color, colorHover const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; - if(isDarkMode) [color, colorHover] = ["#616161", "#909090"]; + if (isDarkMode) [color, colorHover] = ["#616161", "#909090"]; else [color, colorHover] = ["#aaaaaa", "#717171"]; const style = document.createElement("style"); - if(ImprovedTube.storage.comments_sidebar_scrollbars === true){ + if (ImprovedTube.storage.comments_sidebar_scrollbars === true){ const cssRule = ` #primary, #secondary { overflow: overlay !important; @@ -284,12 +284,12 @@ ImprovedTube.commentsSidebar = function() { if(ImprovedTube.storage.comments_sid document.head.appendChild(style); } } - function applyObserver(){ + function applyObserver (){ const debouncedResizePlayer = debounce(resizePlayer, 200); const resizeObserver = new ResizeObserver(debouncedResizePlayer); resizeObserver.observe(video); } - function debounce(callback, delay) { + function debounce (callback, delay) { let timerId; return function (...args) { clearTimeout(timerId); @@ -319,7 +319,7 @@ ImprovedTube.chapters = function (el){ if (ImprovedTube.storage.chapters === tru ImprovedTube.livechat = function () { if (this.storage.livechat === "collapsed") { if (typeof isCollapsed === 'undefined') { var isCollapsed = false; } - if(ImprovedTube.elements.livechat && !isCollapsed){ + if (ImprovedTube.elements.livechat && !isCollapsed){ ImprovedTube.elements.livechat.button.click(); isCollapsed = true } @@ -362,7 +362,7 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { var video = ImprovedTube.elements.video, svg = this.children[0]; - function matchLoopState(opacity) { + function matchLoopState (opacity) { svg.style.opacity = opacity; if (ImprovedTube.storage.player_repeat_button === true) { var otherButton = document.querySelector('#it-repeat-button'); @@ -425,13 +425,13 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { ------------------------------------------------------------------------------*/ ImprovedTube.expandDescription = function (el) { if (this.storage.description === "expanded" || this.storage.description === "classic_expanded") { - if (el) {el.click(); setTimeout(function(){ImprovedTube.elements.player.focus();}, 1200); } + if (el) {el.click(); setTimeout(function (){ImprovedTube.elements.player.focus();}, 1200); } else { var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} // ...except when it is an embedded player? var waitForDescription = setInterval(() => { if (++tries >= maxTries) { el = document.querySelector('#description-inline-expander') - if ( el) { el.click(); setTimeout(function(){ImprovedTube.elements.player.focus(); }, 1200); clearInterval(waitForDescription); } + if ( el) { el.click(); setTimeout(function (){ImprovedTube.elements.player.focus(); }, 1200); clearInterval(waitForDescription); } intervalMs *= 1.11; }}, intervalMs); } } @@ -465,7 +465,7 @@ ImprovedTube.dayOfWeek = function () { if (this.storage.day_of_week === true) { label.textContent = days[tempDate.getDay() + 1] + ' '; label.className = "ytd-day-of-week"; //update please: - try {document.querySelector("#info span:nth-child(2)")?.append(label);} catch { try {document.querySelector("#info #info-strings yt-formatted-string")?.append(label);}catch {}} + try {document.querySelector("#info span:nth-child(2)")?.append(label);} catch { try {document.querySelector("#info #info-strings yt-formatted-string")?.append(label);} catch {}} } // else { element.textContent = days[tempDate.getDay() + 1] + ", "; } }, 4321); } @@ -479,7 +479,7 @@ ImprovedTube.howLongAgoTheVideoWasUploaded = function () { key = this.storage["google-api-key"] || ImprovedTube.defaultApiKey, id = this.getParam(location.href.slice(location.href.indexOf("?") + 1), "v"); - function timeSince(date) { + function timeSince (date) { var seconds = Math.floor((new Date() - new Date(date)) / 1000), interval = Math.floor(seconds / 31536000); @@ -594,7 +594,7 @@ if (ImprovedTube.storage.header_transparent2 === true) { } }); - function handleScroll() { + function handleScroll () { var scrollTop = window.pageYOffset || document.documentElement.scrollTop; var buttonsContainer = document.getElementById('buttons'); @@ -610,9 +610,9 @@ if (ImprovedTube.storage.header_transparent2 === true) { ------------------------------------------------------------------------------*/ window.addEventListener("scroll", handleScroll); - function getScrollDirection() { + function getScrollDirection () { var lastScrollTop = 0; - return function() { + return function () { var st = window.pageYOffset || document.documentElement.scrollTop; var scrollDirection = st > lastScrollTop ? 'down' : 'up'; lastScrollTop = st <= 0 ? 0 : st; @@ -622,7 +622,7 @@ if (ImprovedTube.storage.header_transparent2 === true) { var scrollDirection = getScrollDirection(); - window.addEventListener('scroll', function() { + window.addEventListener('scroll', function () { var direction = scrollDirection(); if (direction === 'down') { document.documentElement.setAttribute('data-scroll-direction', 'down'); diff --git a/js&css/web-accessible/www.youtube.com/blocklist.js b/js&css/web-accessible/www.youtube.com/blocklist.js index e3b82abe1..2e9f083d0 100644 --- a/js&css/web-accessible/www.youtube.com/blocklist.js +++ b/js&css/web-accessible/www.youtube.com/blocklist.js @@ -142,7 +142,7 @@ ImprovedTube.blocklistChannel = function (node) { // YT tries to remove all forein nodes from node.parentNode.parentNode some time after 'yt-navigate-finish' // Need to monitor for it and re-appendChild our button, otherwise if gets deleted when switching to // channel subpages /playlists /featured /videos etc. - this.blocklistChannelObserver = new MutationObserver(function(mutationList) { + this.blocklistChannelObserver = new MutationObserver(function (mutationList) { if (!button.isConnected) { node.parentNode.parentNode.appendChild(button); } @@ -228,7 +228,7 @@ ImprovedTube.blocklistObserver = new MutationObserver(function (mutationList) { }); ImprovedTube.blocklistElementTypeHelper = function (node) { - switch(node.parentNode.className.replace('style-scope ', '')) { + switch (node.parentNode.className.replace('style-scope ', '')) { case 'ytd-compact-video-renderer': // list next to player // node.parentNode.__dataHost.$.dismissible; diff --git a/js&css/web-accessible/www.youtube.com/channel.js b/js&css/web-accessible/www.youtube.com/channel.js index 3eb3aa87c..9db32ce5f 100644 --- a/js&css/web-accessible/www.youtube.com/channel.js +++ b/js&css/web-accessible/www.youtube.com/channel.js @@ -67,7 +67,7 @@ ImprovedTube.channelCompactTheme = function () { if (compact.styles.length) removeStyles() compact = {} } - function styleWithInterval() { + function styleWithInterval () { compact.listener = setInterval(() => { let item = document.querySelector(`#sections ytd-guide-section-renderer:nth-child(4) #items`) if (item) { @@ -77,7 +77,7 @@ ImprovedTube.channelCompactTheme = function () { }, 250) } - function styleWithListeners() { + function styleWithListeners () { compact.parents = [] compact.subs = [] for (let i = 0; i <= 2; i++) { @@ -106,7 +106,7 @@ ImprovedTube.channelCompactTheme = function () { removeStyles(); } - function removeListeners(){ // EventListeners + function removeListeners (){ // EventListeners for (let i = 0; i <= 2; i++) { const parent = compact.parents[i] const sub = compact.subs[i] @@ -116,14 +116,14 @@ ImprovedTube.channelCompactTheme = function () { compact.eventHandlerFns = [] } - function initialLoad() { + function initialLoad () { for (let i = 0; i <= 2; i++) { let isCompact = localStorage.getItem(`ImprovedTube-compact-${i + 2}`) === "true" isCompact ? appendStyle(i) : (compact.styles[i] = null); } } - function appendStyle(index) { // adds style tag + function appendStyle (index) { // adds style tag const cssRules = ` #sections > ytd-guide-section-renderer:nth-child(${index + 2}) > #items{ display:none; @@ -134,7 +134,7 @@ ImprovedTube.channelCompactTheme = function () { document.head.appendChild(compact.styles[index]); } - function removeStyles(){ // styles tags + function removeStyles (){ // styles tags for (let i = 0; i <= compact.styles.length; i++){ if (compact.styles[i] && compact.styles[i].parentNode) { document.head.removeChild(compact.styles[i]); diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index 6b8820783..7005b556d 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -25,7 +25,7 @@ ImprovedTube.autoplayDisable = function (videoElement) { // channel homepage & !channel_trailer_autoplay || (this.storage.channel_trailer_autoplay === false && this.regex.channel.test(location.href)))) { - setTimeout(function() { + setTimeout(function () { try { player.pauseVideo(); } catch (error) { console.log("autoplayDisable: Pausing"); videoElement.pause(); } }); } else { @@ -143,10 +143,10 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); // (Tags/keywords shouldnt lie & very few songs titles might have these words) if (DATA.duration) { - function parseDuration(duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); + function parseDuration (duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); return h * 3600 + m * 60 + s; } DATA.lengthSeconds = parseDuration(DATA.duration); } - function testSongDuration(s, ytMusic) { + function testSongDuration (s, ytMusic) { if (135 <= s && s <= 260) {return 'veryCommon';} if (105 <= s && s <= 420) {return 'common';} if (420 <= s && s <= 720) {return 'long';} @@ -195,7 +195,7 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; } catch {}} if ( DATA.title === ImprovedTube.videoTitle() ) - { keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if(!keywords){keyword=''} ImprovedTube.speedException(); } + { keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if (!keywords){keyword=''} ImprovedTube.speedException(); } else { keywords = ''; (async function () { try { const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`); const htmlContent = await response.text(); @@ -214,10 +214,10 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ else { //Invidious instances. Should be updated automatically!... const invidiousInstances = ['invidious.fdn.fr', 'inv.tux.pizza', 'invidious.flokinet.to', 'invidious.protokolla.fi', 'invidious.private.coffee', 'yt.artemislena.eu', 'invidious.perennialte.ch', 'invidious.materialio.us', 'iv.datura.network']; - function getRandomInvidiousInstance() { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} + function getRandomInvidiousInstance () { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} (async function () { let retries = 4; let invidiousFetched = false; - async function fetchInvidiousData() { + async function fetchInvidiousData () { try {const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); DATA = await response.json(); if (DATA.genre && DATA.title && DATA.keywords && DATA.lengthSeconds) { if (DATA.keywords.toString() === defaultKeywords ) {DATA.keywords = ''} @@ -226,7 +226,7 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ } while (retries > 0 && !invidiousFetched) { await fetchInvidiousData(); if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; } } - if(!invidiousFetched){ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} + if (!invidiousFetched){ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} else { ImprovedTube.fetchDOMData();} } })(); } @@ -241,7 +241,7 @@ ImprovedTube.playerSubtitles = function () { const player = this.elements.player; if (player && player.isSubtitlesOn && player.toggleSubtitles && player.toggleSubtitlesOn) { - switch(this.storage.player_subtitles) { + switch (this.storage.player_subtitles) { case true: case 'enabled': player.toggleSubtitlesOn(); @@ -317,7 +317,7 @@ ImprovedTube.subtitlesUserSettings = function () { for (const value of userSettings) { setting = null; - switch(value) { + switch (value) { case 'fontFamily': case 'fontSizeIncrement': case 'charEdgeStyle': @@ -387,7 +387,7 @@ ImprovedTube.playerAds = function (parent) { let button = parent.querySelector('.ytp-ad-skip-button-modern.ytp-button,[class*="ytp-ad-skip-button"].ytp-button') || parent; // TODO: Replace this with centralized video element pointer let video = document.querySelector('.video-stream.html5-main-video') || false; - function skipAd() { + function skipAd () { if (video) video.currentTime = video.duration; if (button) button.click(); } @@ -404,7 +404,7 @@ ImprovedTube.playerAds = function (parent) { } else if (this.storage.ads === 'small_creators'){ let userDefiniedLimit = this.storage.smallCreatorsCount * parseInt(this.storage.smallCreatorsUnit); let subscribersNumber = ImprovedTube.subscriberCount; - if(subscribersNumber > userDefiniedLimit){ + if (subscribersNumber > userDefiniedLimit){ skipAd(); } } @@ -430,7 +430,7 @@ ImprovedTube.playerQuality = function (quality = this.storage.player_quality) { && player && player.getAvailableQualityLevels && (!player.dataset.defaultQuality || player.dataset.defaultQuality != quality)) { let available_quality_levels = player.getAvailableQualityLevels(); - function closest(num, arr) { + function closest (num, arr) { let curr = arr[0]; let diff = Math.abs(num - curr); for (let val = 1; val < arr.length; val++) { @@ -707,7 +707,7 @@ ImprovedTube.playerRepeatButton = function () { opacity: transparentOrOn, onclick: function () { var video = ImprovedTube.elements.video; - function matchLoopState(opacity) { + function matchLoopState (opacity) { var thisButton = document.querySelector('#it-repeat-button'); thisButton.style.opacity = opacity; if (ImprovedTube.storage.below_player_loop !== false) { @@ -813,7 +813,7 @@ ImprovedTube.playerFitToWinButton = function () { CINEMA MODE BUTTON ------------------------------------------------------------------------------*/ -var xpath = function(xpathToExecute){ +var xpath = function (xpathToExecute){ var result = []; var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); for ( var i=0; i < nodesSnapshot.snapshotLength; i++ ){ @@ -822,7 +822,7 @@ var xpath = function(xpathToExecute){ return result; } -function createOverlay() { +function createOverlay () { var overlay = document.createElement('div'); overlay.id = 'overlay_cinema'; overlay.style.position = 'fixed'; @@ -918,7 +918,7 @@ ImprovedTube.playerCinemaModeEnable = function () { /*------------------------------------------------------------------------------ HAMBURGER MENU ------------------------------------------------------------------------------*/ -ImprovedTube.playerHamburgerButton = function () { if(this.storage.player_hamburger_button === true){ +ImprovedTube.playerHamburgerButton = function () { if (this.storage.player_hamburger_button === true){ const videoPlayer = document.querySelector('.html5-video-player'); if (!videoPlayer) { @@ -996,7 +996,7 @@ ImprovedTube.playerPopupButton = function () { '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${ytPlayer.offsetWidth / 3},height=${ytPlayer.offsetHeight / 3}` ); - if(popup && listMatch){ + if (popup && listMatch){ //! If the video is not in the playlist or not within the first 200 entries, then it automatically selects the first video in the list. popup.addEventListener('load', function () { "use strict"; @@ -1043,9 +1043,9 @@ ImprovedTube.playerControls = function () { player.onmouseenter = player.showControls; player.onmouseleave = player.hideControls; - player.onmousemove = (function() { + player.onmousemove = (function () { let thread, - onmousestop = function() { + onmousestop = function () { if (document.querySelector(".ytp-progress-bar:hover")) { thread = setTimeout(onmousestop, 1000); } else { @@ -1053,7 +1053,7 @@ ImprovedTube.playerControls = function () { } }; - return function() { + return function () { player.showControls(); clearTimeout(thread); thread = setTimeout(onmousestop, 1000); @@ -1458,7 +1458,7 @@ ImprovedTube.pauseWhileTypingOnYoutube = function () { if (ImprovedTube.storage. } }); - function isPlayerInViewport() { + function isPlayerInViewport () { var player = ImprovedTube.elements.player; if (player) { var rect = player.getBoundingClientRect(); diff --git a/js&css/web-accessible/www.youtube.com/playlist.js b/js&css/web-accessible/www.youtube.com/playlist.js index 8a09cf296..d77b8cba0 100644 --- a/js&css/web-accessible/www.youtube.com/playlist.js +++ b/js&css/web-accessible/www.youtube.com/playlist.js @@ -19,7 +19,7 @@ ImprovedTube.playlistUpNextAutoplay = function () { if (this.storage.playlist_up ------------------------------------------------------------------------------*/ ImprovedTube.playlistReverse = function () { if (this.storage.playlist_reverse === true) { - function update() { + function update () { var results = ImprovedTube.elements.ytd_watch.data.contents.twoColumnWatchNextResults, playlist = results.playlist.playlist, autoplay = results.autoplay.autoplay; diff --git a/js&css/web-accessible/www.youtube.com/settings.js b/js&css/web-accessible/www.youtube.com/settings.js index d2ae70ba8..20bd387dd 100644 --- a/js&css/web-accessible/www.youtube.com/settings.js +++ b/js&css/web-accessible/www.youtube.com/settings.js @@ -32,7 +32,7 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { var x2 = event.layerX, y2 = event.layerY; - function mousemove(event) { + function mousemove (event) { if (button.className.indexOf('dragging') === -1) { button.classList.add('it-button--dragging'); } @@ -44,14 +44,14 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { button.style.top = y + 'px'; } - function mouseup() { + function mouseup () { localStorage.setItem('improvedtube-button-position', JSON.stringify({x, y})); window.removeEventListener('mousemove', mousemove); window.removeEventListener('mouseup', mouseup); } - function click() { + function click () { button.classList.remove('it-button--dragging'); window.removeEventListener('click', click); diff --git a/js&css/web-accessible/www.youtube.com/shortcuts.js b/js&css/web-accessible/www.youtube.com/shortcuts.js index be822f93c..0c04088b0 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -72,7 +72,7 @@ ImprovedTube.shortcuts = function () { } }; - function handler() { + function handler () { for (const [key, shortcut] of Object.entries(ImprovedTube.input.listening)) { if ((ImprovedTube.input.pressed.keys && ImprovedTube.input.pressed.keys.length === shortcut.keys.length @@ -107,7 +107,7 @@ ImprovedTube.shortcuts = function () { const camelName = name.replace(/_(.)/g, (m, l) => l.toUpperCase()); let potentialShortcut = {}; for (const button of ['alt', 'ctrl', 'shift', 'wheel', 'keys']) { - switch(button) { + switch (button) { case 'alt': case 'ctrl': case 'shift': @@ -421,15 +421,15 @@ ImprovedTube.shortcutActivateCaptions = function () { }; /*------Chapters------*/ ImprovedTube.shortcutChapters = function () { - try{var height = document.querySelector('*[target-id*=chapters]').clientHeight;}catch{} - if (height) {try{document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close")} catch{}} - else { try{document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open")} catch{} } + try {var height = document.querySelector('*[target-id*=chapters]').clientHeight;} catch {} + if (height) {try {document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close")} catch {}} + else { try {document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open")} catch {} } }; /*------Transcript------*/ ImprovedTube.shortcutTranscript = function () { - try{var height = document.querySelector('*[target-id*=transcript]').clientHeight;}catch{} - if (height) {try{document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close")} catch{}} - else { try{document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open")} catch{} } + try {var height = document.querySelector('*[target-id*=transcript]').clientHeight;} catch {} + if (height) {try {document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close")} catch {}} + else { try {document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open")} catch {} } }; /*------------------------------------------------------------------------------ 4.7.22 LIKE @@ -445,19 +445,19 @@ ImprovedTube.shortcutDislike = function () { }; /*------Report------*/ ImprovedTube.shortcutReport = function () { - try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); + try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} - catch{console.log("'...' failed"); setTimeout(function(){try{document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} - catch{console.log("'...' failed2")}}, 100) } + catch {console.log("'...' failed"); setTimeout(function (){try {document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} + catch {console.log("'...' failed2")}}, 100) } - setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} - catch{console.log("report failed"); setTimeout(function() {try{document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} - catch{console.log("report failed2"); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}}, 800); + setTimeout(function (){try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} + catch {console.log("report failed"); setTimeout(function () {try {document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} + catch {console.log("report failed2"); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}}, 800); } }, 200); - setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed"); - setTimeout(function(){try{document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)}catch{console.log("dropdown visible failed2");}}, 1700)}}, 700) + setTimeout(function (){try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed"); + setTimeout(function (){try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed2");}}, 1700)}}, 700) } /*------------------------------------------------------------------------------ 4.7.24 SUBSCRIBE @@ -490,7 +490,7 @@ Loop ImprovedTube.shortcutToggleLoop = function () { const video = this.elements.video, player = this.elements.player; - function matchLoopState(opacity) { + function matchLoopState (opacity) { document.querySelector('#it-repeat-button')?.children[0]?.style.setProperty("opacity", opacity); document.querySelector('#it-below-player-loop')?.children[0]?.style.setProperty("opacity", opacity); }; @@ -525,7 +525,7 @@ ImprovedTube.shortcutStatsForNerds = function () { 4.7.28 TOGGLE CARDS ------------------------------------------------------------------------------*/ ImprovedTube.shortcutToggleCards = function () { - function toggleVideoOverlays() { + function toggleVideoOverlays () { document.documentElement.toggleAttribute('it-player-hide-cards'); document.documentElement.toggleAttribute('it-player-hide-endcards'); document.documentElement.toggleAttribute('it-hide-video-title-fullScreen'); diff --git a/js&css/web-accessible/www.youtube.com/themes.js b/js&css/web-accessible/www.youtube.com/themes.js index c63d6464c..7763f229f 100644 --- a/js&css/web-accessible/www.youtube.com/themes.js +++ b/js&css/web-accessible/www.youtube.com/themes.js @@ -81,7 +81,7 @@ ImprovedTube.myColors = function () { } ImprovedTube.setTheme = function () { - switch(this.storage.theme) { + switch (this.storage.theme) { case 'dark': document.documentElement.setAttribute('dark', ''); document.querySelector('ytd-masthead')?.setAttribute('dark', ''); diff --git a/menu/satus.js b/menu/satus.js index 83f81f6c6..6ab9503f7 100644 --- a/menu/satus.js +++ b/menu/satus.js @@ -122,7 +122,7 @@ var satus = { # BASICS --------------------------------------------------------------*/ /*--CAMELIZE--------------------------------------------------*/ -satus.camelize = function(string) { +satus.camelize = function (string) { var result = ''; for (var i = 0, l = string.length; i < l; i++) { var character = string[i]; @@ -138,11 +138,11 @@ satus.camelize = function(string) { return result; }; /*---SNAKELIZE-------------------------------------------------*/ -satus.snakelize = function(string) { +satus.snakelize = function (string) { return string.replace(/([A-Z])/g, '-$1').toLowerCase(); }; /*---SORT------------------------------------------------------*/ -satus.sort = function(array, order, property) { +satus.sort = function (array, order, property) { var type; if (property) { @@ -154,21 +154,21 @@ satus.sort = function(array, order, property) { if (order !== 'desc') { if (type === 'number') { if (property) { - return array.sort(function(a, b) { + return array.sort(function (a, b) { return a[property] - b[property]; }); } else { - return array.sort(function(a, b) { + return array.sort(function (a, b) { return a - b; }); } } else if (type === 'string') { if (property) { - return array.sort(function(a, b) { + return array.sort(function (a, b) { return a[property].localeCompare(b[property]); }); } else { - return array.sort(function(a, b) { + return array.sort(function (a, b) { return a.localeCompare(b); }); } @@ -176,21 +176,21 @@ satus.sort = function(array, order, property) { } else { if (type === 'number') { if (property) { - return array.sort(function(a, b) { + return array.sort(function (a, b) { return b[property] - a[property]; }); } else { - return array.sort(function(a, b) { + return array.sort(function (a, b) { return b - a; }); } } else if (type === 'string') { if (property) { - return array.sort(function(a, b) { + return array.sort(function (a, b) { return b[property].localeCompare(a[property]); }); } else { - return array.sort(function(a, b) { + return array.sort(function (a, b) { return b.localeCompare(a); }); } @@ -198,7 +198,7 @@ satus.sort = function(array, order, property) { } }; /*---data------------------------------------------------------*/ -satus.data = function(element, data) { +satus.data = function (element, data) { if (data) { for (var key in data) { var value = data[key]; @@ -212,9 +212,9 @@ satus.data = function(element, data) { } }; /*---# ISSET-----------------------------------------------------*/ -satus.isset = function(target, is_object) { +satus.isset = function (target, is_object) { if (is_object === true) { - var keys = target.split('.').filter(function(value) { + var keys = target.split('.').filter(function (value) { return value != ''; }); @@ -239,17 +239,17 @@ satus.isset = function(target, is_object) { /*------------------------------------------------------------- # is___(target) --------------------------------------------------------------*/ -satus.isFunction =function(target){return typeof target ==='function';}; +satus.isFunction =function (target){return typeof target ==='function';}; satus.isArray = Array.isArray; -satus.isString = function(t) { return typeof t ==='string'; }; -satus.isNumber = function(t) { return (typeof t ==='number' && !isNaN(t)); }; -satus.isObject = function(t) { return (t instanceof Object && t !== null); }; -satus.isElement = function(t) { return (t instanceof Element || t instanceof HTMLDocument); }; -satus.isNodeList = function(t) { return t instanceof NodeList; }; -satus.isBoolean = function(t) { return (t === false || t === true); }; +satus.isString = function (t) { return typeof t ==='string'; }; +satus.isNumber = function (t) { return (typeof t ==='number' && !isNaN(t)); }; +satus.isObject = function (t) { return (t instanceof Object && t !== null); }; +satus.isElement = function (t) { return (t instanceof Element || t instanceof HTMLDocument); }; +satus.isNodeList = function (t) { return t instanceof NodeList; }; +satus.isBoolean = function (t) { return (t === false || t === true); }; /*---LOG------------------------------------------------------*/ -satus.log =function(){console.log.apply(null, arguments);}; +satus.log =function (){console.log.apply(null, arguments);}; /*-------------------------------------------------------------- @@ -259,13 +259,13 @@ satus.log =function(){console.log.apply(null, arguments);}; /*-------------------------------------------------------------- # APPEND --------------------------------------------------------------*/ -satus.append = function(child, parent) { +satus.append = function (child, parent) { (parent || document.body).appendChild(child); }; /*-------------------------------------------------------------- # ATTR setAttributes --------------------------------------------------------------*/ -satus.setAttributes = satus.attr = function(element, attributes) { +satus.setAttributes = satus.attr = function (element, attributes) { if (attributes) { for (var name in attributes) { var value = attributes[name]; @@ -293,7 +293,7 @@ satus.setAttributes = satus.attr = function(element, attributes) { /*-------------------------------------------------------------- # CLONE --------------------------------------------------------------*/ -satus.clone = function(item) { +satus.clone = function (item) { var clone = item.cloneNode(true), parent_css = window.getComputedStyle(item.parentNode), css = window.getComputedStyle(item), @@ -319,7 +319,7 @@ satus.clone = function(item) { /*-------------------------------------------------------------- # CREATE ELEMENT --------------------------------------------------------------*/ -satus.createElement = function(tagName, componentName, namespaceURI) { +satus.createElement = function (tagName, componentName, namespaceURI) { var camelizedTagName = this.camelize(tagName), className = 'satus-' + (componentName || tagName), element, @@ -346,7 +346,7 @@ satus.createElement = function(tagName, componentName, namespaceURI) { element.componentName = componentName; element.className = className; - element.createChildElement = function(tagName, componentName, namespaceURI) { + element.createChildElement = function (tagName, componentName, namespaceURI) { var element = satus.createElement(tagName, this.componentName + '__' + (componentName || tagName), namespaceURI); if (this.baseProvider) { @@ -367,7 +367,7 @@ satus.createElement = function(tagName, componentName, namespaceURI) { /*-------------------------------------------------------------- # EMPTY --------------------------------------------------------------*/ -satus.empty = function(element, exclude = []) { +satus.empty = function (element, exclude = []) { for (var i = element.childNodes.length - 1; i > -1; i--) { var child = element.childNodes[i]; @@ -380,7 +380,7 @@ satus.empty = function(element, exclude = []) { /*-------------------------------------------------------------- # ELEMENT INDEX --------------------------------------------------------------*/ -satus.elementIndex = function(element) { +satus.elementIndex = function (element) { return Array.prototype.slice.call(element.parentNode.children).indexOf(element); }; @@ -389,13 +389,13 @@ satus.elementIndex = function(element) { # CSS --------------------------------------------------------------*/ -satus.css = function(element, property) { +satus.css = function (element, property) { return window.getComputedStyle(element).getPropertyValue(property); }; /*-------------------------------------------------------------- # CLASS --------------------------------------------------------------*/ -satus.addClass = satus.class = function(element, className) { +satus.addClass = satus.class = function (element, className) { if (className) { element.classList.add(className); } @@ -403,7 +403,7 @@ satus.addClass = satus.class = function(element, className) { /*-------------------------------------------------------------- # STYLE --------------------------------------------------------------*/ -satus.style = function(element, object) { +satus.style = function (element, object) { if (object) { for (var key in object) { element.style[key] = object[key]; @@ -413,7 +413,7 @@ satus.style = function(element, object) { /*-------------------------------------------------------------- # ANIMATION DURATION --------------------------------------------------------------*/ -satus.getAnimationDuration = function(element) { +satus.getAnimationDuration = function (element) { return Number(window.getComputedStyle(element).getPropertyValue('animation-duration').replace(/[^0-9.]/g, '')) * 1000; }; @@ -425,7 +425,7 @@ satus.getAnimationDuration = function(element) { /*-------------------------------------------------------------- # DECRYPTION --------------------------------------------------------------*/ -satus.decrypt = async function(text, password) { +satus.decrypt = async function (text, password) { var iv = text.slice(0, 24).match(/.{2}/g).map(byte => parseInt(byte, 16)), algorithm = { name: 'AES-GCM', @@ -452,7 +452,7 @@ satus.decrypt = async function(text, password) { /*-------------------------------------------------------------- # ENCRYPTION --------------------------------------------------------------*/ -satus.encrypt = async function(text, password) { +satus.encrypt = async function (text, password) { var iv = crypto.getRandomValues(new Uint8Array(12)), algorithm = { name: 'AES-GCM', @@ -470,7 +470,7 @@ satus.encrypt = async function(text, password) { --------------------------------------------------------------*/ /*-- ON ------------------------------------------------------*/ -satus.events.on = function(type, handler) { +satus.events.on = function (type, handler) { if (!this.data[type]) { this.data[type] = []; } @@ -478,7 +478,7 @@ satus.events.on = function(type, handler) { this.data[type].push(handler); }; /*-- TRIGGER ------------------------------------------------*/ -satus.events.trigger = function(type, data) { +satus.events.trigger = function (type, data) { var handlers = this.data[type]; if (handlers) { @@ -491,7 +491,7 @@ satus.events.trigger = function(type, data) { /*-------------------------------------------------------------- # FETCH --------------------------------------------------------------*/ -satus.fetch = function(url, success, error, type) { +satus.fetch = function (url, success, error, type) { fetch(url) .then(response => response.ok ? response[type || 'json']().then(success) : error()) .catch(() => error(success)); @@ -499,7 +499,7 @@ satus.fetch = function(url, success, error, type) { /*-------------------------------------------------------------- # GET PROPERTY --------------------------------------------------------------*/ -satus.getProperty = function(object, string) { +satus.getProperty = function (object, string) { var properties = string.split('.'); for (var i = 0, l = properties.length; i < l; i++) { @@ -521,7 +521,7 @@ satus.getProperty = function(object, string) { # INDEX OF --------------------------------------------------------------*/ -satus.indexOf = function(child, parent) { +satus.indexOf = function (child, parent) { var index = 0; if (satus.isArray(parent)) { @@ -539,7 +539,7 @@ satus.indexOf = function(child, parent) { # TO INDEX --------------------------------------------------------------*/ -satus.toIndex = function(index, child, parent) { +satus.toIndex = function (index, child, parent) { if (satus.isArray(parent)) { parent.splice(index, 0, parent.splice(satus.indexOf(child, parent), 1)[0]) } @@ -548,7 +548,7 @@ satus.toIndex = function(index, child, parent) { # ON --------------------------------------------------------------*/ -satus.on = function(element, listeners) { +satus.on = function (element, listeners) { if (listeners) { for (var type in listeners) { if (type == 'parentObject') { @@ -564,7 +564,7 @@ satus.on = function(element, listeners) { if (satus.isFunction(listener)) { element.addEventListener(type, listener); } else if (satus.isArray(listener) || satus.isObject(listener)) { - element.addEventListener(type, function(event) { + element.addEventListener(type, function (event) { var target = this.skeleton.on[event.type], layers = this.layersProvider; @@ -584,7 +584,7 @@ satus.on = function(element, listeners) { } }); } else if (satus.isString(listener)) { - element.addEventListener(type, function() { + element.addEventListener(type, function () { let match = this.skeleton.on[event.type].match(/(["'`].+["'`]|[^.()]+)/g), target = this.baseProvider; @@ -623,7 +623,7 @@ satus.on = function(element, listeners) { # PARENTIFY --------------------------------------------------------------*/ -satus.parentify = function(parentObject, exclude) { +satus.parentify = function (parentObject, exclude) { for (var key in parentObject) { if (exclude.indexOf(key) === -1) { var child = parentObject[key]; @@ -646,7 +646,7 @@ satus.parentify = function(parentObject, exclude) { /*-------------------------------------------------------------- # PREPEND --------------------------------------------------------------*/ -satus.prepend = function(child, parent) { +satus.prepend = function (child, parent) { if (this.isElement(child)) { parent.prepend(child); } else if (this.isObject(child)) { @@ -656,7 +656,7 @@ satus.prepend = function(child, parent) { /*-------------------------------------------------------------- # PROPERTIES --------------------------------------------------------------*/ -satus.properties = function(element, properties) { +satus.properties = function (element, properties) { if (properties) { for (var key in properties) { var property = properties[key]; @@ -672,7 +672,7 @@ satus.properties = function(element, properties) { /*-------------------------------------------------------------- # REMOVE --------------------------------------------------------------*/ -satus.remove = function(child, parent) { +satus.remove = function (child, parent) { if (satus.isArray(parent)) { parent.splice(satus.indexOf(child, parent), 1); } @@ -680,7 +680,7 @@ satus.remove = function(child, parent) { /*-------------------------------------------------------------- # RENDER --------------------------------------------------------------*/ -satus.render = function(skeleton, container, property, childrenOnly, prepend, skip_children) { +satus.render = function (skeleton, container, property, childrenOnly, prepend, skip_children) { var element; if (skeleton.component && childrenOnly !== true) { @@ -744,7 +744,7 @@ satus.render = function(skeleton, container, property, childrenOnly, prepend, sk // dont add storage component to storage: false elements if (skeleton.storage != false) { - element.storage = (function() { + element.storage = (function () { var parent = element, key = skeleton.storage || property || false, value; @@ -765,18 +765,18 @@ satus.render = function(skeleton, container, property, childrenOnly, prepend, sk return Object.defineProperties({}, { key: { - get: function() { + get: function () { return key; }, - set: function(string) { + set: function (string) { key = string; } }, value: { - get: function() { + get: function () { return value; }, - set: function(val) { + set: function (val) { value = val; if (satus.storage.get(key) != val) { @@ -788,7 +788,7 @@ satus.render = function(skeleton, container, property, childrenOnly, prepend, sk } }); }()); - element.storage.remove = function() { + element.storage.remove = function () { satus.storage.remove(element.storage.key); element.dispatchEvent(new CustomEvent('change')); @@ -854,10 +854,10 @@ satus.render = function(skeleton, container, property, childrenOnly, prepend, sk # CLEAR --------------------------------------------------------------*/ -satus.storage.clear = function(callback) { +satus.storage.clear = function (callback) { this.data = {}; - chrome.storage.local.clear(function() { + chrome.storage.local.clear(function () { satus.events.trigger('storage-clear'); if (callback) { @@ -870,14 +870,14 @@ satus.storage.clear = function(callback) { # GET --------------------------------------------------------------*/ -satus.storage.get = function(key) { +satus.storage.get = function (key) { var target = this.data; if (typeof key !== 'string') { return; } - key = key.split('/').filter(function(value) { + key = key.split('/').filter(function (value) { return value != ''; }); @@ -899,13 +899,13 @@ satus.storage.get = function(key) { /*-------------------------------------------------------------- # IMPORT --------------------------------------------------------------*/ -satus.storage.import = function(keys, callback) { +satus.storage.import = function (keys, callback) { var self = this; if (typeof keys === 'function') { callback = keys; keys = undefined; } - chrome.storage.local.get(keys || null, function(items) { + chrome.storage.local.get(keys || null, function (items) { for (var key in items) { self.data[key] = items[key]; } @@ -918,14 +918,14 @@ satus.storage.import = function(keys, callback) { /*-------------------------------------------------------------- # REMOVE --------------------------------------------------------------*/ -satus.storage.remove = function(key, callback) { +satus.storage.remove = function (key, callback) { var target = this.data; if (typeof key !== 'string') { return; } - key = key.split('/').filter(function(value) { + key = key.split('/').filter(function (value) { return value != ''; }); @@ -944,7 +944,7 @@ satus.storage.remove = function(key, callback) { if (key.length === 1) { chrome.storage.local.remove(key[0]); } else { - chrome.storage.local.set(this.data, function() { + chrome.storage.local.set(this.data, function () { satus.events.trigger('storage-remove'); if (callback) { @@ -957,7 +957,7 @@ satus.storage.remove = function(key, callback) { /*-------------------------------------------------------------- # SET --------------------------------------------------------------*/ -satus.storage.set = function(key, value, callback) { +satus.storage.set = function (key, value, callback) { var items = {}, target = this.data; @@ -965,7 +965,7 @@ satus.storage.set = function(key, value, callback) { return; } - key = key.split('/').filter(function(value) { + key = key.split('/').filter(function (value) { return value != ''; }); @@ -986,7 +986,7 @@ satus.storage.set = function(key, value, callback) { } } - chrome.storage.local.set({[key]: value}, function() { + chrome.storage.local.set({[key]: value}, function () { satus.events.trigger('storage-set'); if (callback) { @@ -998,8 +998,8 @@ satus.storage.set = function(key, value, callback) { /*-------------------------------------------------------------- # ON CHANGED --------------------------------------------------------------*/ -satus.storage.onchanged = function(callback) { - chrome.storage.onChanged.addListener(function(changes) { +satus.storage.onchanged = function (callback) { + chrome.storage.onChanged.addListener(function (changes) { for (var key in changes) { callback(key, changes[key].newValue); } @@ -1010,7 +1010,7 @@ satus.storage.onchanged = function(callback) { # LAST --------------------------------------------------------------*/ -satus.last = function(variable) { +satus.last = function (variable) { if (this.isArray(variable) || this.isNodeList(variable) || variable instanceof HTMLCollection) { return variable[variable.length - 1]; } @@ -1024,15 +1024,15 @@ satus.last = function(variable) { /*-------------------------------------------------------------- # GET --------------------------------------------------------------*/ -satus.locale.get = function(string) { +satus.locale.get = function (string) { return this.data[string] || string; }; /*-------------------------------------------------------------- # IMPORT // old: satus.locale.import(url, onload, onsuccess); --------------------------------------------------------------*/ -satus.locale.import = function(code, callback, path) { +satus.locale.import = function (code, callback, path) { // if (!path) { path = '_locales/'; } - function importLocale(locale, successCallback) { + function importLocale (locale, successCallback) { var url = chrome.runtime.getURL(path + locale + '/messages.json'); fetch(url) .then(response => response.ok ? response.json() : {}) @@ -1054,7 +1054,7 @@ satus.locale.import = function(code, callback, path) { importLocale(language, () => importLocale('en', callback)); } } else { // try chrome://settings/languages: - try{chrome.i18n.getAcceptLanguages(function (languages) { + try {chrome.i18n.getAcceptLanguages(function (languages) { languages = languages.map(language => language.replace('-', '_')); for (let i = languages.length - 1; i >= 0; i--) { if (languages[i].includes('_')) { @@ -1074,7 +1074,7 @@ satus.locale.import = function(code, callback, path) { languages.length === 3 && importLocale(languages[0], () => importLocale(languages[1], () => importLocale(languages[2], callback))); ... */ // console.log(languages); - });} catch(error) { + });} catch (error) { // Finally, if code nor chrome://settings/languages are available, use window.navigator.language: let language = window.navigator.language.replace('-', '_'); @@ -1091,7 +1091,7 @@ satus.locale.import = function(code, callback, path) { # TEXT --------------------------------------------------------------*/ -satus.text = function(element, value) { +satus.text = function (element, value) { if (value) { if (satus.isFunction(value)) { value = value(); @@ -1103,23 +1103,23 @@ satus.text = function(element, value) { /*-------------------------------------------------------------- >>> MODAL --------------------------------------------------------------*/ -satus.components.modal = function(component, skeleton) { +satus.components.modal = function (component, skeleton) { component.scrim = component.createChildElement('div', 'scrim'); component.surface = component.createChildElement('div', 'surface'); - component.close = function() { + component.close = function () { var component = this; this.classList.add('satus-modal--closing'); - setTimeout(function() { + setTimeout(function () { component.remove(); component.dispatchEvent(new CustomEvent('close')); }, Number(satus.css(this.surface, 'animation-duration').replace(/[^0-9.]/g, '')) * 1000); }; - component.scrim.addEventListener('click', function() { + component.scrim.addEventListener('click', function () { // this is someone clicking outside of modal dialog switch (skeleton.variant) { case 'confirm': @@ -1171,7 +1171,7 @@ satus.components.modal = function(component, skeleton) { /*-------------------------------------------------------------- # CONFIRM --------------------------------------------------------------*/ -satus.components.modal.confirm = function(component, skeleton) { +satus.components.modal.confirm = function (component, skeleton) { component.surface.actions = satus.render({ component: 'section', variant: 'align-end' @@ -1194,7 +1194,7 @@ satus.components.modal.confirm = function(component, skeleton) { modalProvider: component, }, on: { - click: function() { + click: function () { // cancel() is optional in modal.confirm simplified variant if (this.modalProvider.skeleton.cancel && satus.isFunction(this.modalProvider.skeleton.cancel)) { this.modalProvider.skeleton.cancel(); @@ -1210,7 +1210,7 @@ satus.components.modal.confirm = function(component, skeleton) { modalProvider: component, }, on: { - click: function() { + click: function () { // ok() is optional in modal.confirm simplified variant if (this.modalProvider.skeleton.ok && satus.isFunction(this.modalProvider.skeleton.ok)) { this.modalProvider.skeleton.ok(); @@ -1225,14 +1225,14 @@ satus.components.modal.confirm = function(component, skeleton) { /*-------------------------------------------------------------- >>> GRID --------------------------------------------------------------*/ -satus.components.grid = function(component, skeleton) { +satus.components.grid = function (component, skeleton) { console.log(component, skeleton); }; /*-------------------------------------------------------------- >>> TEXT FIELD --------------------------------------------------------------*/ -satus.components.textField = function(component, skeleton) { +satus.components.textField = function (component, skeleton) { var container = component.createChildElement('div', 'container'), input = container.createChildElement(skeleton.rows === 1 ? 'input' : 'textarea'), display = container.createChildElement('div', 'display'), @@ -1258,14 +1258,14 @@ satus.components.textField = function(component, skeleton) { component.syntax = { current: 'text', handlers: { - regex: function(value, target) { + regex: function (value, target) { var regex_token = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, char_class_token = /[^\\-]+|-|\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)/g, char_class_parts = /^(\[\^?)(]?(?:[^\\\]]+|\\[\S\s]?)*)(]?)$/, quantifier = /^(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??$/, matches = value.match(regex_token); - function create(type, string) { + function create (type, string) { var span = document.createElement('span'); span.className = type; @@ -1297,7 +1297,7 @@ satus.components.textField = function(component, skeleton) { } } }, - set: function(syntax) { + set: function (syntax) { if (this.handlers[syntax]) { this.current = syntax; } else { @@ -1307,7 +1307,7 @@ satus.components.textField = function(component, skeleton) { pre.update(); } }; - component.focus = function() { + component.focus = function () { this.autofocus = true; this.input.focus(); }; @@ -1326,10 +1326,10 @@ satus.components.textField = function(component, skeleton) { } Object.defineProperty(component, 'value', { - get: function() { + get: function () { return this.input.value; }, - set: function(value) { + set: function (value) { this.input.value = value; this.dispatchEvent(new CustomEvent('change')); @@ -1346,7 +1346,7 @@ satus.components.textField = function(component, skeleton) { selection.setAttribute('disabled', ''); - line_numbers.update = function() { + line_numbers.update = function () { var component = this.parentNode.parentNode.parentNode, count = component.input.value.split('\n').length; @@ -1365,7 +1365,7 @@ satus.components.textField = function(component, skeleton) { component.input.style.paddingLeft = this.offsetWidth + 'px'; }; - pre.update = function() { + pre.update = function () { var component = this.parentNode.parentNode.parentNode, handler = component.syntax.handlers[component.syntax.current], value = component.value || ''; @@ -1391,7 +1391,7 @@ satus.components.textField = function(component, skeleton) { } }; - cursor.update = function() { + cursor.update = function () { var component = this.parentNode.parentNode.parentNode, input = component.input, value = input.value, @@ -1442,7 +1442,7 @@ satus.components.textField = function(component, skeleton) { }; // global listener, make sure we remove when element no longer exists - function selectionchange(event) { + function selectionchange (event) { if (!document.body.contains(component)) { document.removeEventListener('selectionchange', selectionchange); return; @@ -1454,7 +1454,7 @@ satus.components.textField = function(component, skeleton) { document.addEventListener('selectionchange', selectionchange); - input.addEventListener('input', function() { + input.addEventListener('input', function () { var component = this.parentNode.parentNode; if (component.skeleton.storage) { @@ -1466,7 +1466,7 @@ satus.components.textField = function(component, skeleton) { component.cursor.update(); }); - input.addEventListener('scroll', function(event) { + input.addEventListener('scroll', function (event) { var component = this.parentNode.parentNode; component.display.style.top = -this.scrollTop + 'px'; @@ -1477,20 +1477,20 @@ satus.components.textField = function(component, skeleton) { component.cursor.update(); }); - component.addEventListener('change', function() { + component.addEventListener('change', function () { this.lineNumbers.update(); this.pre.update(); this.cursor.update(); }); - component.addEventListener('render', function() { + component.addEventListener('render', function () { this.lineNumbers.update(); this.pre.update(); this.cursor.update(); }); if (skeleton.on?.blur) { - input.addEventListener('blur', function(event) { + input.addEventListener('blur', function (event) { this.parentNode.parentNode.dispatchEvent(new Event(event.type)); }); } @@ -1505,7 +1505,7 @@ satus.components.textField = function(component, skeleton) { /*-------------------------------------------------------------- # CORE --------------------------------------------------------------*/ -satus.components.chart = function(component, skeleton) { +satus.components.chart = function (component, skeleton) { var type = skeleton.type; if (this.chart[type]) { @@ -1518,7 +1518,7 @@ satus.components.chart = function(component, skeleton) { /*-------------------------------------------------------------- # BAR --------------------------------------------------------------*/ -satus.components.chart.bar = function(component, skeleton) { +satus.components.chart.bar = function (component, skeleton) { var labels = skeleton.labels, datasets = skeleton.datasets, bars = []; @@ -1565,7 +1565,7 @@ satus.components.chart.bar = function(component, skeleton) { /*-------------------------------------------------------------- >>> SELECT --------------------------------------------------------------*/ -satus.components.select = function(component, skeleton) { +satus.components.select = function (component, skeleton) { var content = component.createChildElement('div', 'content'); component.childrenContainer = content; @@ -1598,15 +1598,15 @@ satus.components.select = function(component, skeleton) { } Object.defineProperty(component, 'value', { - get() { + get () { return this.selectElement.value; }, - set(value) { + set (value) { this.selectElement.value = value; } }); - component.render = function() { + component.render = function () { satus.empty(this.valueElement); if (this.selectElement.options[this.selectElement.selectedIndex]) { @@ -1616,7 +1616,7 @@ satus.components.select = function(component, skeleton) { this.dataset.value = this.value; }; - component.selectElement.addEventListener('change', function() { + component.selectElement.addEventListener('change', function () { var component = this.parentNode; component.storage.value = this.value; @@ -1632,12 +1632,12 @@ satus.components.select = function(component, skeleton) { /*-------------------------------------------------------------- >>> DIVIDER --------------------------------------------------------------*/ -satus.components.divider = function() {}; +satus.components.divider = function () {}; /*-------------------------------------------------------------- >>> SECTION --------------------------------------------------------------*/ -satus.components.section = function(component, skeleton) { +satus.components.section = function (component, skeleton) { if (satus.isString(skeleton.title)) { component.dataset.title = satus.locale.get(skeleton.title); } @@ -1646,7 +1646,7 @@ satus.components.section = function(component, skeleton) { >>> BASE --------------------------------------------------------------*/ -satus.components.base = function(component) { +satus.components.base = function (component) { component.baseProvider = component; component.layers = []; }; @@ -1654,11 +1654,11 @@ satus.components.base = function(component) { >>> ALERT --------------------------------------------------------------*/ -satus.components.alert = function(component, skeleton) {}; +satus.components.alert = function (component, skeleton) {}; /*-------------------------------------------------------------- >>> TIME --------------------------------------------------------------*/ -satus.components.time = function(component, skeleton) { +satus.components.time = function (component, skeleton) { var select_skeleton = Object.assign({}, skeleton); select_skeleton.component = 'select'; @@ -1705,17 +1705,17 @@ satus.components.time = function(component, skeleton) { /*-------------------------------------------------------------- >>> SIDEBAR --------------------------------------------------------------*/ -satus.components.sidebar = function(component, skeleton) {}; +satus.components.sidebar = function (component, skeleton) {}; /*-------------------------------------------------------------- >>> LAYERS --------------------------------------------------------------*/ -satus.components.layers = function(component, skeleton) { +satus.components.layers = function (component, skeleton) { component.path = []; component.renderChildren = false; component.baseProvider.layers.push(component); component.layersProvider = component; - component.back = function() { + component.back = function () { if (this.path.length > 1) { this.path.pop(); @@ -1723,7 +1723,7 @@ satus.components.layers = function(component, skeleton) { } }; - component.open = function(skeleton, history) { + component.open = function (skeleton, history) { var previous_layer = satus.last(this.querySelectorAll('.satus-layers__layer')), layer = this.createChildElement('div', 'layer'); @@ -1740,7 +1740,7 @@ satus.components.layers = function(component, skeleton) { } if (previous_layer) { - setTimeout(function() { + setTimeout(function () { previous_layer.remove(); }, satus.getAnimationDuration(previous_layer)); } @@ -1753,7 +1753,7 @@ satus.components.layers = function(component, skeleton) { this.dispatchEvent(new Event('open')); }; - component.update = function() { + component.update = function () { var layer = this.querySelector('.satus-layers__layer'); satus.empty(layer); @@ -1766,7 +1766,7 @@ satus.components.layers = function(component, skeleton) { >>> LIST --------------------------------------------------------------*/ -satus.components.list = function(component, skeleton) { +satus.components.list = function (component, skeleton) { for (const item of skeleton.items) { const li = component.createChildElement('div', 'item'); @@ -1785,17 +1785,17 @@ satus.components.list = function(component, skeleton) { >>> COLOR PICKER --------------------------------------------------------------*/ -satus.components.colorPicker = function(component, skeleton) { +satus.components.colorPicker = function (component, skeleton) { component.childrenContainer = component.createChildElement('div', 'content'); - component.color = (function(element) { + component.color = (function (element) { var array; Object.defineProperty(element, 'value', { - get: function() { + get: function () { return array; }, - set: function(value) { + set: function (value) { array = value; element.style.backgroundColor = 'rgb(' + value.join(',') + ')'; @@ -1807,7 +1807,7 @@ satus.components.colorPicker = function(component, skeleton) { return element; })(component.createChildElement('span', 'value')); - component.addEventListener('click', function() { + component.addEventListener('click', function () { var hsl = satus.color.rgbToHsl(this.color.value), s = hsl[1] / 100, l = hsl[2] / 100; @@ -1831,7 +1831,7 @@ satus.components.colorPicker = function(component, skeleton) { 'backgroundColor': 'hsl(' + hsl[0] + 'deg, 100%, 50%)' }, on: { - mousedown: function(event) { + mousedown: function (event) { if (event.button !== 0) { return false; } @@ -1840,7 +1840,7 @@ satus.components.colorPicker = function(component, skeleton) { rect = this.getBoundingClientRect(), cursor = this.children[0]; - function mousemove(event) { + function mousemove (event) { var hsl = palette.skeleton.parentSkeleton.value, x = event.clientX - rect.left, y = event.clientY - rect.top, @@ -1863,7 +1863,7 @@ satus.components.colorPicker = function(component, skeleton) { event.preventDefault(); } - function mouseup() { + function mouseup () { window.removeEventListener('mousemove', mousemove); window.removeEventListener('mouseup', mouseup); } @@ -1900,7 +1900,7 @@ satus.components.colorPicker = function(component, skeleton) { value: hsl[0], max: 360, on: { - input: function() { + input: function () { var modal = this.skeleton.parentSkeleton.parentSkeleton, hsl = modal.value; @@ -1920,7 +1920,7 @@ satus.components.colorPicker = function(component, skeleton) { component: 'button', text: 'reset', on: { - click: function() { + click: function () { var modal = this.skeleton.parentSkeleton.parentSkeleton, component = modal.parentElement; @@ -1935,7 +1935,7 @@ satus.components.colorPicker = function(component, skeleton) { component: 'button', text: 'cancel', on: { - click: function() { + click: function () { this.skeleton.parentSkeleton.parentSkeleton.rendered.close(); } } @@ -1944,7 +1944,7 @@ satus.components.colorPicker = function(component, skeleton) { component: 'button', text: 'OK', on: { - click: function() { + click: function () { var modal = this.skeleton.parentSkeleton.parentSkeleton, component = modal.parentElement; @@ -1963,7 +1963,7 @@ satus.components.colorPicker = function(component, skeleton) { >>> RADIO --------------------------------------------------------------*/ -satus.components.radio = function(component, skeleton) { +satus.components.radio = function (component, skeleton) { let value; component.nativeControl = component.createChildElement('input', 'input'); @@ -1991,7 +1991,7 @@ satus.components.radio = function(component, skeleton) { component.nativeControl.checked = true; } - component.nativeControl.addEventListener('change', function() { + component.nativeControl.addEventListener('change', function () { const component = this.parentNode, parent = component.parentNode.parentNode.skeleton; let defValue; @@ -2025,7 +2025,7 @@ satus.components.radio = function(component, skeleton) { >>> SLIDER --------------------------------------------------------------*/ -satus.components.slider = function(component, skeleton) { +satus.components.slider = function (component, skeleton) { var content = component.createChildElement('div', 'content'), children_container = content.createChildElement('div', 'children-container'), text_input = content.createChildElement('input'), @@ -2045,7 +2045,7 @@ satus.components.slider = function(component, skeleton) { input.step = skeleton.step || 1; input.value = component.storage?.value || skeleton.value || 0; - text_input.addEventListener('blur', function() { + text_input.addEventListener('blur', function () { var component = this.parentNode.parentNode; component.input.value = Number(this.value.replace(/[^0-9.]/g, '')); @@ -2053,7 +2053,7 @@ satus.components.slider = function(component, skeleton) { component.update(); }); - text_input.addEventListener('keydown', function(event) { + text_input.addEventListener('keydown', function (event) { if (event.key === 'Enter') { var component = this.parentNode.parentNode; @@ -2063,7 +2063,7 @@ satus.components.slider = function(component, skeleton) { } }); - input.addEventListener('input', function() { + input.addEventListener('input', function () { var component = this.parentNode.parentNode; component.value = Number(this.value); @@ -2071,7 +2071,7 @@ satus.components.slider = function(component, skeleton) { component.update(); }); - component.update = function() { + component.update = function () { const input = this.input; this.textInput.value = input.value; @@ -2090,7 +2090,7 @@ satus.components.slider = function(component, skeleton) { if (skeleton.on) { for (var type in skeleton.on) { - input.addEventListener(type, function(event) { + input.addEventListener(type, function (event) { this.parentNode.parentNode.dispatchEvent(new Event(event.type)); }); } @@ -2100,7 +2100,7 @@ satus.components.slider = function(component, skeleton) { >>> TABS --------------------------------------------------------------*/ -satus.components.tabs = function(component, skeleton) { +satus.components.tabs = function (component, skeleton) { let tabs = skeleton.items, value = skeleton.value; @@ -2115,7 +2115,7 @@ satus.components.tabs = function(component, skeleton) { for (const tab of tabs) { const button = component.createChildElement('button'); - button.addEventListener('click', function() { + button.addEventListener('click', function () { const component = this.parentNode, index = satus.elementIndex(this); @@ -2134,18 +2134,18 @@ satus.components.tabs = function(component, skeleton) { >>> SHORTCUT --------------------------------------------------------------*/ -satus.components.shortcut = function(component, skeleton) { +satus.components.shortcut = function (component, skeleton) { component.childrenContainer = component.createChildElement('div', 'content'); component.valueElement = component.createChildElement('div', 'value'); component.className = 'satus-button'; - component.render = function(parent = this.primary) { + component.render = function (parent = this.primary) { let children = parent.children; satus.empty(parent); - function createElement(name) { + function createElement (name) { var element = document.createElement('div'); element.className = 'satus-shortcut__' + name; @@ -2246,7 +2246,7 @@ satus.components.shortcut = function(component, skeleton) { } }; - component.keydown = function(event) { + component.keydown = function (event) { event.preventDefault(); event.stopPropagation(); @@ -2272,7 +2272,7 @@ satus.components.shortcut = function(component, skeleton) { }; if (skeleton.wheel !== false) { - component.mousewheel = function(event) { + component.mousewheel = function (event) { event.stopPropagation(); if ( @@ -2303,7 +2303,7 @@ satus.components.shortcut = function(component, skeleton) { }; } - component.addEventListener('click', function() { + component.addEventListener('click', function () { satus.render({ component: 'modal', variant: 'shortcut', @@ -2311,7 +2311,7 @@ satus.components.shortcut = function(component, skeleton) { parent: this }, on: { - close: function() { + close: function () { window.removeEventListener('keydown', component.keydown); window.removeEventListener('wheel', component.mousewheel); } @@ -2321,11 +2321,11 @@ satus.components.shortcut = function(component, skeleton) { component: 'div', class: 'satus-shortcut__primary', on: { - render: function() { + render: function () { component.primary = this; if (component.skeleton.mouseButtons === true) { - this.addEventListener('mousedown', function(event) { + this.addEventListener('mousedown', function (event) { if ( component.data.click && event.button === 0 || component.data.middle && event.button === 1 @@ -2353,7 +2353,7 @@ satus.components.shortcut = function(component, skeleton) { } }); - this.addEventListener('contextmenu', function(event) { + this.addEventListener('contextmenu', function (event) { event.preventDefault(); event.stopPropagation(); @@ -2388,7 +2388,7 @@ satus.components.shortcut = function(component, skeleton) { component: 'button', text: 'reset', on: { - click: function() { + click: function () { var component = this.parentNode.parentNode.parentNode.parent; component.data = component.skeleton.value || {}; @@ -2407,7 +2407,7 @@ satus.components.shortcut = function(component, skeleton) { component: 'button', text: 'cancel', on: { - click: function() { + click: function () { component.data = satus.storage.get(component.storage.key) || component.skeleton.value || {}; component.render(component.valueElement); @@ -2423,7 +2423,7 @@ satus.components.shortcut = function(component, skeleton) { component: 'button', text: 'save', on: { - click: function() { + click: function () { component.storage.value = component.data; component.render(component.valueElement); @@ -2456,7 +2456,7 @@ satus.components.shortcut = function(component, skeleton) { >>> CHECKBOX --------------------------------------------------------------*/ -satus.components.checkbox = function(component, skeleton) { +satus.components.checkbox = function (component, skeleton) { component.input = component.createChildElement('input'); component.input.type = 'checkbox'; @@ -2467,7 +2467,7 @@ satus.components.checkbox = function(component, skeleton) { component.dataset.value = component.storage.value || skeleton.value; component.input.checked = component.storage.value || skeleton.value; - component.input.addEventListener('change', function() { + component.input.addEventListener('change', function () { var component = this.parentNode; if (this.checked === true) { @@ -2483,7 +2483,7 @@ satus.components.checkbox = function(component, skeleton) { >>> SWITCH --------------------------------------------------------------*/ -satus.components.switch = function(component, skeleton) { +satus.components.switch = function (component, skeleton) { var value = satus.isset(component.storage.value) ? component.storage.value : skeleton.value; if (satus.isFunction(value)) { @@ -2499,14 +2499,14 @@ satus.components.switch = function(component, skeleton) { // 'custom' disables default onclick, user provided function should handle this functionality manually if (!skeleton.custom) { - component.addEventListener('click', function() { + component.addEventListener('click', function () { this.flip(); }, true); } }; -satus.components.switch.flip = function(val) { - switch(val) { +satus.components.switch.flip = function (val) { + switch (val) { case true: this.dataset.value = 'true'; this.storage.value = true; @@ -2529,9 +2529,9 @@ satus.components.switch.flip = function(val) { /*-------------------------------------------------------------- >>> CONTEXT MENU --------------------------------------------------------------*/ -satus.events.on('render', function(component) { +satus.events.on('render', function (component) { if (component.skeleton.contextMenu) { - component.addEventListener('contextmenu', function(event) { + component.addEventListener('contextmenu', function (event) { var base = this.baseProvider, base_rect = base.getBoundingClientRect(), x = event.clientX - base_rect.left, @@ -2572,9 +2572,9 @@ satus.events.on('render', function(component) { >>> SORTABLE --------------------------------------------------------------*/ -satus.events.on('render', function(component) { +satus.events.on('render', function (component) { if (component.skeleton.sortable === true) { - component.addEventListener('mousedown', function(event) { + component.addEventListener('mousedown', function (event) { if (event.button !== 0) { return false; } @@ -2591,7 +2591,7 @@ satus.events.on('render', function(component) { ghost.classList.add('satus-sortable__ghost'); - function mousemove(event) { + function mousemove (event) { if (appended === false && (Math.abs(event.clientX - x) > 4 || Math.abs(event.clientY - y) > 4)) { appended = true; @@ -2603,7 +2603,7 @@ satus.events.on('render', function(component) { ghost.style.transform = 'translate(' + (event.clientX - offset_x) + 'px, ' + (event.clientY - offset_y) + 'px)'; } - function mouseup(event) { + function mouseup (event) { component.classList.remove('satus-sortable__chosen'); ghost.remove(); @@ -2635,7 +2635,7 @@ satus.events.on('render', function(component) { capture: true }); - function siblingMouseOver(event) { + function siblingMouseOver (event) { var parent = this.parentNode, y = event.layerY / (this.offsetHeight / 100); @@ -2665,7 +2665,7 @@ satus.events.on('render', function(component) { >>> MANIFEST --------------------------------------------------------------*/ -satus.manifest = function() { +satus.manifest = function () { var object = {}; if (this.isset('chrome.runtime.getManifest')) { @@ -2689,7 +2689,7 @@ satus.color = {}; # STRING TO ARRAY --------------------------------------------------------------*/ -satus.color.stringToArray = function(string) { +satus.color.stringToArray = function (string) { var match = string.match(/[0-9.]+/g); if (match) { @@ -2705,7 +2705,7 @@ satus.color.stringToArray = function(string) { # RGB TO HSL --------------------------------------------------------------*/ -satus.color.rgbToHsl = function(array) { +satus.color.rgbToHsl = function (array) { var r = array[0] / 255, g = array[1] / 255, b = array[2] / 255, @@ -2749,7 +2749,7 @@ satus.color.rgbToHsl = function(array) { # HUE TO RGB --------------------------------------------------------------*/ -satus.color.hueToRgb = function(array) { +satus.color.hueToRgb = function (array) { var t1 = array[0], t2 = array[1], hue = array[2]; @@ -2777,7 +2777,7 @@ satus.color.hueToRgb = function(array) { # HSL TO RGB --------------------------------------------------------------*/ -satus.color.hslToRgb = function(array) { +satus.color.hslToRgb = function (array) { var h = array[0] / 360, s = array[1] / 100, l = array[2] / 100, @@ -2786,7 +2786,7 @@ satus.color.hslToRgb = function(array) { if (s == 0) { r = g = b = l; } else { - var hue2rgb = function(p, q, t) { + var hue2rgb = function (p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; @@ -2845,7 +2845,7 @@ satus.user = { # NAME --------------------------------------------------------------*/ -satus.user.os.name = function() { +satus.user.os.name = function () { var app_version = navigator.appVersion; if (app_version.indexOf('Win') !== -1) { @@ -2885,7 +2885,7 @@ satus.user.os.name = function() { # BITNESS --------------------------------------------------------------*/ -satus.user.os.bitness = function() { +satus.user.os.bitness = function () { if (navigator.appVersion.match(/(Win64|x64|x86_64|WOW64)/)) { return '64-bit'; } else { @@ -2901,7 +2901,7 @@ satus.user.os.bitness = function() { # NAME --------------------------------------------------------------*/ -satus.user.browser.name = function() { +satus.user.browser.name = function () { var user_agent = navigator.userAgent; if (navigator.brave) { return 'Brave'; @@ -2928,7 +2928,7 @@ satus.user.browser.name = function() { # VERSION --------------------------------------------------------------*/ -satus.user.browser.version = function() { +satus.user.browser.version = function () { var browser_name = satus.user.browser.name(), browser_version = navigator.userAgent.match(new RegExp(browser_name + '/([0-9.]+)')); @@ -2939,7 +2939,7 @@ satus.user.browser.version = function() { # PLATFORM --------------------------------------------------------------*/ -satus.user.browser.platform = function() { +satus.user.browser.platform = function () { return navigator.platform; }; @@ -2947,7 +2947,7 @@ satus.user.browser.platform = function() { # MANIFEST --------------------------------------------------------------*/ -satus.user.browser.manifest = function() { +satus.user.browser.manifest = function () { return chrome.runtime.getManifest() || {}; }; @@ -2955,7 +2955,7 @@ satus.user.browser.manifest = function() { # LANGUAGES --------------------------------------------------------------*/ -satus.user.browser.languages = function() { +satus.user.browser.languages = function () { return navigator.languages; }; @@ -2963,7 +2963,7 @@ satus.user.browser.languages = function() { # COOKIES --------------------------------------------------------------*/ -satus.user.browser.cookies = function() { +satus.user.browser.cookies = function () { if (document.cookie) { var random_cookie = 'nX6cMXKWsc'; @@ -2981,7 +2981,7 @@ satus.user.browser.cookies = function() { # FLASH --------------------------------------------------------------*/ -satus.user.browser.flash = function() { +satus.user.browser.flash = function () { try { if (new ActiveXObject('ShockwaveFlash.ShockwaveFlash')) { return true; @@ -2999,7 +2999,7 @@ satus.user.browser.flash = function() { # JAVA --------------------------------------------------------------*/ -satus.user.browser.java = function() { +satus.user.browser.java = function () { if (satus.isFunction(navigator.javaEnabled) && navigator.javaEnabled()) { return true; } else { @@ -3011,7 +3011,7 @@ satus.user.browser.java = function() { # AUDIO --------------------------------------------------------------*/ -satus.user.browser.audio = function() { +satus.user.browser.audio = function () { var audio = document.createElement('audio'), types = { mp3: 'audio/mpeg', @@ -3039,7 +3039,7 @@ satus.user.browser.audio = function() { # VIDEO --------------------------------------------------------------*/ -satus.user.browser.video = function() { +satus.user.browser.video = function () { var video = document.createElement('video'), types = { //ogg: 'video/ogg; codecs="theora"', @@ -3069,7 +3069,7 @@ satus.user.browser.video = function() { # WEBGL --------------------------------------------------------------*/ -satus.user.browser.webgl = function() { +satus.user.browser.webgl = function () { var cvs = document.createElement('canvas'), ctx = cvs.getContext('webgl'); @@ -3084,7 +3084,7 @@ satus.user.browser.webgl = function() { # SCREEN --------------------------------------------------------------*/ -satus.user.device.screen = function() { +satus.user.device.screen = function () { if (screen) { return screen.width + 'x' + screen.height; } @@ -3094,7 +3094,7 @@ satus.user.device.screen = function() { # RAM --------------------------------------------------------------*/ -satus.user.device.ram = function() { +satus.user.device.ram = function () { if ('deviceMemory' in navigator) { return navigator.deviceMemory + ' GB'; } @@ -3104,7 +3104,7 @@ satus.user.device.ram = function() { # GPU --------------------------------------------------------------*/ -satus.user.device.gpu = function() { +satus.user.device.gpu = function () { var cvs = document.createElement('canvas'), ctx = cvs.getContext('webgl'); @@ -3126,7 +3126,7 @@ satus.user.device.gpu = function() { # CORES --------------------------------------------------------------*/ -satus.user.device.cores = function() { +satus.user.device.cores = function () { return navigator.deviceConcurrency || navigator.hardwareConcurrency; }; @@ -3134,7 +3134,7 @@ satus.user.device.cores = function() { # TOUCH --------------------------------------------------------------*/ -satus.user.device.touch = function() { +satus.user.device.touch = function () { var result = {}; if ( @@ -3154,7 +3154,7 @@ satus.user.device.touch = function() { # CONNECTION --------------------------------------------------------------*/ -satus.user.device.connection = function() { +satus.user.device.connection = function () { var result = {}; if (typeof navigator.connection === 'object') { @@ -3171,7 +3171,7 @@ satus.user.device.connection = function() { # SEARCH --------------------------------------------------------------*/ -satus.search = function(query, object, callback) { +satus.search = function (query, object, callback) { const included = ['switch', 'select', 'slider', 'shortcut', 'radio', 'color-picker', 'label', 'button'], excluded = [ 'baseProvider', @@ -3188,7 +3188,7 @@ satus.search = function(query, object, callback) { query = query.toLowerCase(); - function parse(items, parent) { + function parse (items, parent) { threads++; for (const [key, item] of Object.entries(items)) { @@ -3225,7 +3225,7 @@ satus.search = function(query, object, callback) { /*-------------------------------------------------------------- # count --------------------------------------------------------------*/ -function createInput(placeholder, onChange) { +function createInput (placeholder, onChange) { const input = document.createElement('input'); input.type = 'number'; input.placeholder = placeholder; @@ -3233,7 +3233,7 @@ function createInput(placeholder, onChange) { return input; } -function createSelect(options, changeHandler) { +function createSelect (options, changeHandler) { const select = document.createElement('select'); for (const optionData of options) { diff --git a/menu/skeleton-parts/dark-light-switch.js b/menu/skeleton-parts/dark-light-switch.js index f8f276d05..90aa72e8c 100644 --- a/menu/skeleton-parts/dark-light-switch.js +++ b/menu/skeleton-parts/dark-light-switch.js @@ -8,7 +8,7 @@ const isDark = () => { extension.skeleton.header.sectionEnd.darkLightSwitch.svgSun.on = { render: function () { console.log(satus.storage.get('lastLightTheme') + " " + satus.storage.get('lastDarkTheme')) - if(isDark()) { + if (isDark()) { this.style.display = 'none' } } @@ -16,7 +16,7 @@ extension.skeleton.header.sectionEnd.darkLightSwitch.svgSun.on = { extension.skeleton.header.sectionEnd.darkLightSwitch.svgMoon.on = { render: function () { - if(!isDark()) { + if (!isDark()) { this.style.display = 'none' } } @@ -24,7 +24,7 @@ extension.skeleton.header.sectionEnd.darkLightSwitch.svgMoon.on = { extension.skeleton.header.sectionEnd.darkLightSwitch.on = { click: function () { - if(isDark()) { + if (isDark()) { if (satus.storage.get('lastLightTheme')) { satus.storage.set('theme', satus.storage.get("lastLightTheme")) } else { @@ -45,7 +45,7 @@ extension.skeleton.header.sectionEnd.darkLightSwitch.on = { } satus.storage.onchanged(() => { - if(isDark()) { + if (isDark()) { document.getElementById('dark-light-switch-icon-sun').style.display = 'none' document.getElementById('dark-light-switch-icon-moon').style.display = '' satus.storage.set('lastDarkTheme', satus.storage.get('theme')) diff --git a/menu/skeleton-parts/search.js b/menu/skeleton-parts/search.js index 4f8e32ce3..0678117e2 100644 --- a/menu/skeleton-parts/search.js +++ b/menu/skeleton-parts/search.js @@ -134,7 +134,7 @@ extension.skeleton.header.sectionEnd.search.on.click = { search_results = satus.render(skeleton, self.baseProvider); // we need global listener here - function hidesearch(event) { + function hidesearch (event) { // make sure to clean it after closing search results if (!document.body.contains(search_results)) { document.removeEventListener('click', hidesearch); From 226ae9d7e7f266b735f071c1adc41015dca597ad Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 23:30:49 +0800 Subject: [PATCH 15/17] Update js-lint-test.yml --- .github/workflows/js-lint-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/js-lint-test.yml b/.github/workflows/js-lint-test.yml index 6d19ce8ee..dee96500b 100644 --- a/.github/workflows/js-lint-test.yml +++ b/.github/workflows/js-lint-test.yml @@ -24,7 +24,7 @@ jobs: node-version: '20' - name: Install dependencies - run: npm install + run: npm install --force - name: Run eslint run: npx eslint From 839702557e8f27396e946fbf1dd18de8ec550507 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 23:45:21 +0800 Subject: [PATCH 16/17] Add space-before-blocks check --- background.js | 2 +- eslint.config.mjs | 5 +-- js&css/extension/init.js | 2 +- .../www.youtube.com/general/general.js | 8 ++--- js&css/web-accessible/functions.js | 8 ++--- js&css/web-accessible/init.js | 6 ++-- .../www.youtube.com/appearance.js | 34 +++++++++---------- .../web-accessible/www.youtube.com/channel.js | 6 ++-- .../web-accessible/www.youtube.com/player.js | 20 +++++------ .../www.youtube.com/playlist.js | 10 +++--- .../www.youtube.com/shortcuts.js | 8 ++--- menu/satus.js | 4 +-- 12 files changed, 57 insertions(+), 56 deletions(-) diff --git a/background.js b/background.js index 7359ae5de..977ff9f00 100644 --- a/background.js +++ b/background.js @@ -94,7 +94,7 @@ chrome.runtime.onInstalled.addListener(function (installed) { } }); } else if (installed.reason == 'install') { - if (navigator.userAgent.indexOf("Firefox") != -1){ + if (navigator.userAgent.indexOf("Firefox") != -1) { chrome.storage.local.set({below_player_pip: false})} if (navigator.userAgent.indexOf('Safari') !== -1 && (!/Windows|Chrom/.test(navigator.userAgent) diff --git a/eslint.config.mjs b/eslint.config.mjs index 330f2c895..79d954db2 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -3,8 +3,8 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import js from "@eslint/js"; import { FlatCompat } from "@eslint/eslintrc"; -import { fixupConfigRules } from '@eslint/compat' -import eslintPluginCompat from 'eslint-plugin-compat' +import { fixupConfigRules } from '@eslint/compat'; +import eslintPluginCompat from 'eslint-plugin-compat'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -49,6 +49,7 @@ export default [...compat.extends("eslint:recommended"), ...compatConfiguration, "no-multiple-empty-lines": ["error", {"max": 1, "maxBOF": 0, "maxEOF": 0}], "keyword-spacing": ["warn", { "before": true, "after": true }], "space-before-function-paren": "warn", + "space-before-blocks": "warn", "max-len": ["error", { code: 255, ignoreUrls: true, diff --git a/js&css/extension/init.js b/js&css/extension/init.js index 6ce852cbf..8020cd839 100644 --- a/js&css/extension/init.js +++ b/js&css/extension/init.js @@ -244,5 +244,5 @@ document.addEventListener('it-message-from-youtube', function () { document.addEventListener('it-play', function (event) { var videos = document.querySelectorAll('video'); try {chrome.runtime.sendMessage({action: 'play'})} - catch (error){console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } + catch (error) {console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } }); diff --git a/js&css/extension/www.youtube.com/general/general.js b/js&css/extension/www.youtube.com/general/general.js index 634bcd137..374627927 100644 --- a/js&css/extension/www.youtube.com/general/general.js +++ b/js&css/extension/www.youtube.com/general/general.js @@ -251,13 +251,13 @@ extension.features.popupWindowButtons = function (event) { event.stopPropagation(); try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch (error) { console.log(error)}; ytPlayer = document.querySelector("#movie_player"); - if (ytPlayer){width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} + if (ytPlayer) {width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} else { width = innerWidth * 0.4; height = innerHeight * 0.4; } if (!ytPlayer) { let shorts = /short/.test(this.parentElement.href); if ( width / height < 1 ) { let vertical = true } else { let vertical = false } - if ( !vertical && shorts ){ width = height * 0.6} - if ( vertical && !shorts ){ height = width * 0.6} + if ( !vertical && shorts ) { width = height * 0.6} + if ( vertical && !shorts ) { height = width * 0.6} } window.open('https://www.youtube.com/embed/' + this.dataset.id + '?autoplay=' + (extension.storage.get('player_autoplay_disable') ? '0' : '1'), '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); @@ -528,7 +528,7 @@ extension.features.disableThumbnailPlayback = function (event) { # OPEN VIDEOS IN A NEW TAB --------------------------------------------------------------*/ -extension.features.openNewTab = function (){ +extension.features.openNewTab = function () { if (extension.storage.get("open_new_tab") === true) { window.onload = function () { const searchButton = document.querySelector("button#search-icon-legacy"); diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index b5d276967..edbcbce7c 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -169,7 +169,7 @@ ImprovedTube.ytElementsHandler = function (node) { } } } - if (mutation.type === 'attributes' && mutation.attributeName === 'id' && mutation.target.querySelector('*[id^="ad-text"], *[id^="skip-button"], .ytp-ad-skip-button-modern.ytp-button',)){ + if (mutation.type === 'attributes' && mutation.attributeName === 'id' && mutation.target.querySelector('*[id^="ad-text"], *[id^="skip-button"], .ytp-ad-skip-button-modern.ytp-button',)) { ImprovedTube.playerAds(node); } } @@ -377,7 +377,7 @@ ImprovedTube.playerOnTimeUpdate = function () { } if (ImprovedTube.storage.always_show_progress_bar === true) {ImprovedTube.showProgressBar();} - if (ImprovedTube.storage.player_remaining_duration === true){ImprovedTube.playerRemainingDuration();} + if (ImprovedTube.storage.player_remaining_duration === true) {ImprovedTube.playerRemainingDuration();} ImprovedTube.played_time += .5; }, 500); } @@ -431,7 +431,7 @@ ImprovedTube.onkeydown = function () { ImprovedTube.onmousedown = function () { window.addEventListener('mousedown', function (event) { if (!ImprovedTube.user_interacted) { - setTimeout(function (){ImprovedTube.user_interacted = true}, 3000); + setTimeout(function () {ImprovedTube.user_interacted = true}, 3000); if (ImprovedTube.elements.player && ImprovedTube.elements.player.classList.contains('ad-showing') === false) { var path = event.composedPath(); for (var i = 0, l = path.length; i < l; i++) { @@ -577,7 +577,7 @@ ImprovedTube.createPlayerButton = function (options) { tooltip.style.top = rect.top - 8 + 'px'; tooltip.textContent = this.dataset.title; - if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)){ + if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)) { tooltip.style.zIndex = 10001;} // needed for cinema mode function mouseleave () { tooltip.remove(); diff --git a/js&css/web-accessible/init.js b/js&css/web-accessible/init.js index 3fd9da296..628171893 100644 --- a/js&css/web-accessible/init.js +++ b/js&css/web-accessible/init.js @@ -15,7 +15,7 @@ ImprovedTube.observer = new MutationObserver(function (mutationList) { ImprovedTube.childHandler(mutation.addedNodes[j]); } - for (const node of mutation.removedNodes){ + for (const node of mutation.removedNodes) { if (node.nodeName === 'BUTTON' && node.id === 'it-popup-playlist-button') ImprovedTube.playlistPopupUpdate(); } } @@ -105,8 +105,8 @@ ImprovedTube.init = function () { this.onmousedown(); this.youtubeLanguage(); this.myColors(); - if (this.storage.undo_the_new_sidebar === true){this.undoTheNewSidebar();} - if (this.storage.description === "sidebar"){this.descriptionSidebar();} + if (this.storage.undo_the_new_sidebar === true) {this.undoTheNewSidebar();} + if (this.storage.description === "sidebar") {this.descriptionSidebar();} this.channelCompactTheme(); if (ImprovedTube.elements.player && ImprovedTube.elements.player.setPlaybackRate) { diff --git a/js&css/web-accessible/www.youtube.com/appearance.js b/js&css/web-accessible/www.youtube.com/appearance.js index 857c37e4f..b4485e10b 100644 --- a/js&css/web-accessible/www.youtube.com/appearance.js +++ b/js&css/web-accessible/www.youtube.com/appearance.js @@ -150,7 +150,7 @@ ImprovedTube.playerRemainingDuration = function () { /*------------------------------------------------------------------------------ Comments Sidebar Simple ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebarSimple = function () { if (ImprovedTube.storage.comments_sidebar_simple === true){ +ImprovedTube.commentsSidebarSimple = function () { if (ImprovedTube.storage.comments_sidebar_simple === true) { if (window.matchMedia("(min-width: 1599px)").matches) { document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments"));} if (window.matchMedia("(max-width: 1598px)").matches) { @@ -163,7 +163,7 @@ ImprovedTube.commentsSidebarSimple = function () { if (ImprovedTube.storage.comm /*------------------------------------------------------------------------------ Comments Sidebar ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_sidebar === true){ +ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_sidebar === true) { const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); let hasApplied = 0; if (/watch\?/.test(location.href)) { @@ -174,7 +174,7 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s window.addEventListener("resize", sidebar) } - function sidebar (){ + function sidebar () { resizePlayer(); if (window.matchMedia("(min-width: 1952px)").matches) { @@ -182,7 +182,7 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s initialSetup() setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) } - else if (hasApplied == 2){ //from medium to big size + else if (hasApplied == 2) { //from medium to big size setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) } hasApplied = 1 @@ -191,19 +191,19 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s if (!hasApplied) { initialSetup(); } - else if (hasApplied == 1){ //from big to medium + else if (hasApplied == 1) { //from big to medium document.getElementById("primary-inner").appendChild(document.getElementById("related")); } hasApplied = 2 } else { /// <1000 - if (hasApplied == 1){ + if (hasApplied == 1) { document.getElementById("primary-inner").appendChild(document.getElementById("related")); let comments = document.querySelector("#comments"); let below = document.getElementById("below"); below.appendChild(comments); } - else if (hasApplied == 2){ + else if (hasApplied == 2) { let comments = document.querySelector("#comments"); let below = document.getElementById("below"); below.appendChild(comments); @@ -211,7 +211,7 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s hasApplied = 0; } } - function setGrid (){ + function setGrid () { let checkParentInterval = setInterval(() => { container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; if (container) { @@ -239,14 +239,14 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s document.getElementById("primary").style.width = `${width}px`; player.style.width = `${width}px`; } - function styleScrollbars (){ - if (!navigator.userAgent.toLowerCase().includes("mac")){ + function styleScrollbars () { + if (!navigator.userAgent.toLowerCase().includes("mac")) { let color, colorHover const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; if (isDarkMode) [color, colorHover] = ["#616161", "#909090"]; else [color, colorHover] = ["#aaaaaa", "#717171"]; const style = document.createElement("style"); - if (ImprovedTube.storage.comments_sidebar_scrollbars === true){ + if (ImprovedTube.storage.comments_sidebar_scrollbars === true) { const cssRule = ` #primary, #secondary { overflow: overlay !important; @@ -284,7 +284,7 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s document.head.appendChild(style); } } - function applyObserver (){ + function applyObserver () { const debouncedResizePlayer = debounce(resizePlayer, 200); const resizeObserver = new ResizeObserver(debouncedResizePlayer); resizeObserver.observe(video); @@ -306,12 +306,12 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s /*---------------------------------------------------------------- TRANSCRIPT --------------------------------------------------------------*/ -ImprovedTube.transcript = function (el){ if (ImprovedTube.storage.transcript === true){ +ImprovedTube.transcript = function (el) { if (ImprovedTube.storage.transcript === true) { el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility');} } /*---------------------------------------------------------------- CHAPTERS --------------------------------------------------------------*/ -ImprovedTube.chapters = function (el){ if (ImprovedTube.storage.chapters === true){ +ImprovedTube.chapters = function (el) { if (ImprovedTube.storage.chapters === true) { el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility');} } /*------------------------------------------------------------------------------ LIVECHAT @@ -319,7 +319,7 @@ ImprovedTube.chapters = function (el){ if (ImprovedTube.storage.chapters === tru ImprovedTube.livechat = function () { if (this.storage.livechat === "collapsed") { if (typeof isCollapsed === 'undefined') { var isCollapsed = false; } - if (ImprovedTube.elements.livechat && !isCollapsed){ + if (ImprovedTube.elements.livechat && !isCollapsed) { ImprovedTube.elements.livechat.button.click(); isCollapsed = true } @@ -425,13 +425,13 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { ------------------------------------------------------------------------------*/ ImprovedTube.expandDescription = function (el) { if (this.storage.description === "expanded" || this.storage.description === "classic_expanded") { - if (el) {el.click(); setTimeout(function (){ImprovedTube.elements.player.focus();}, 1200); } + if (el) {el.click(); setTimeout(function () {ImprovedTube.elements.player.focus();}, 1200); } else { var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} // ...except when it is an embedded player? var waitForDescription = setInterval(() => { if (++tries >= maxTries) { el = document.querySelector('#description-inline-expander') - if ( el) { el.click(); setTimeout(function (){ImprovedTube.elements.player.focus(); }, 1200); clearInterval(waitForDescription); } + if ( el) { el.click(); setTimeout(function () {ImprovedTube.elements.player.focus(); }, 1200); clearInterval(waitForDescription); } intervalMs *= 1.11; }}, intervalMs); } } diff --git a/js&css/web-accessible/www.youtube.com/channel.js b/js&css/web-accessible/www.youtube.com/channel.js index 9db32ce5f..f341886eb 100644 --- a/js&css/web-accessible/www.youtube.com/channel.js +++ b/js&css/web-accessible/www.youtube.com/channel.js @@ -106,7 +106,7 @@ ImprovedTube.channelCompactTheme = function () { removeStyles(); } - function removeListeners (){ // EventListeners + function removeListeners () { // EventListeners for (let i = 0; i <= 2; i++) { const parent = compact.parents[i] const sub = compact.subs[i] @@ -134,8 +134,8 @@ ImprovedTube.channelCompactTheme = function () { document.head.appendChild(compact.styles[index]); } - function removeStyles (){ // styles tags - for (let i = 0; i <= compact.styles.length; i++){ + function removeStyles () { // styles tags + for (let i = 0; i <= compact.styles.length; i++) { if (compact.styles[i] && compact.styles[i].parentNode) { document.head.removeChild(compact.styles[i]); } diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index 7005b556d..113f2a215 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -195,7 +195,7 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; } catch {}} if ( DATA.title === ImprovedTube.videoTitle() ) - { keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if (!keywords){keyword=''} ImprovedTube.speedException(); } + { keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if (!keywords) {keyword=''} ImprovedTube.speedException(); } else { keywords = ''; (async function () { try { const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`); const htmlContent = await response.text(); @@ -226,7 +226,7 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ } while (retries > 0 && !invidiousFetched) { await fetchInvidiousData(); if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; } } - if (!invidiousFetched){ if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} + if (!invidiousFetched) { if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} else { ImprovedTube.fetchDOMData();} } })(); } @@ -401,10 +401,10 @@ ImprovedTube.playerAds = function (parent) { if (ImprovedTube.elements.category === 'music') { skipAd(); } - } else if (this.storage.ads === 'small_creators'){ + } else if (this.storage.ads === 'small_creators') { let userDefiniedLimit = this.storage.smallCreatorsCount * parseInt(this.storage.smallCreatorsUnit); let subscribersNumber = ImprovedTube.subscriberCount; - if (subscribersNumber > userDefiniedLimit){ + if (subscribersNumber > userDefiniedLimit) { skipAd(); } } @@ -813,10 +813,10 @@ ImprovedTube.playerFitToWinButton = function () { CINEMA MODE BUTTON ------------------------------------------------------------------------------*/ -var xpath = function (xpathToExecute){ +var xpath = function (xpathToExecute) { var result = []; var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); - for ( var i=0; i < nodesSnapshot.snapshotLength; i++ ){ + for ( var i=0; i < nodesSnapshot.snapshotLength; i++ ) { result.push( nodesSnapshot.snapshotItem(i) ); } return result; @@ -855,7 +855,7 @@ ImprovedTube.playerCinemaModeButton = function () { onclick: function () { var player = xpath('//*[@id="movie_player"]/div[1]/video')[0].parentNode.parentNode // console.log(player) - if (player.style.zIndex == 10000){ + if (player.style.zIndex == 10000) { player.style.zIndex = 1; svg.parentNode.style.opacity = 0.64; svg.parentNode.style.zIndex = 1; @@ -918,7 +918,7 @@ ImprovedTube.playerCinemaModeEnable = function () { /*------------------------------------------------------------------------------ HAMBURGER MENU ------------------------------------------------------------------------------*/ -ImprovedTube.playerHamburgerButton = function () { if (this.storage.player_hamburger_button === true){ +ImprovedTube.playerHamburgerButton = function () { if (this.storage.player_hamburger_button === true) { const videoPlayer = document.querySelector('.html5-video-player'); if (!videoPlayer) { @@ -972,7 +972,7 @@ ImprovedTube.playerHamburgerButton = function () { if (this.storage.player_hambu POPUP PLAYER ------------------------------------------------------------------------------*/ ImprovedTube.playerPopupButton = function () { - if (this.storage.player_popup_button === true && location.href.indexOf('youtube.com/embed') === -1 ){ + if (this.storage.player_popup_button === true && location.href.indexOf('youtube.com/embed') === -1 ) { var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); @@ -996,7 +996,7 @@ ImprovedTube.playerPopupButton = function () { '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${ytPlayer.offsetWidth / 3},height=${ytPlayer.offsetHeight / 3}` ); - if (popup && listMatch){ + if (popup && listMatch) { //! If the video is not in the playlist or not within the first 200 entries, then it automatically selects the first video in the list. popup.addEventListener('load', function () { "use strict"; diff --git a/js&css/web-accessible/www.youtube.com/playlist.js b/js&css/web-accessible/www.youtube.com/playlist.js index d77b8cba0..291b595fd 100644 --- a/js&css/web-accessible/www.youtube.com/playlist.js +++ b/js&css/web-accessible/www.youtube.com/playlist.js @@ -94,7 +94,7 @@ ImprovedTube.playlistReverse = function () { ------------------------------------------------------------------------------*/ ImprovedTube.playlistRepeat = function () { if ( ImprovedTube.storage.playlist_repeat === true ) { - setTimeout(function (){ + setTimeout(function () { var option = ImprovedTube.storage.playlist_repeat, button = document.querySelector("#button.ytd-playlist-loop-button-renderer") || document.querySelector("ytd-playlist-loop-button-renderer button") || document.querySelector("ytd-playlist-loop-button-renderer"); if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M21') @@ -115,7 +115,7 @@ ImprovedTube.playlistRepeat = function () { ------------------------------------------------------------------------------*/ ImprovedTube.playlistShuffle = function () { if ( ImprovedTube.storage.playlist_shuffle === true ) { - setTimeout(function (){ + setTimeout(function () { var button = ImprovedTube.elements.playlist.shuffle_button, option = ImprovedTube.storage.playlist_shuffle; button = document.querySelector('#playlist-actions #playlist-action-menu ytd-toggle-button-renderer'); @@ -188,8 +188,8 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c if (!ImprovedTube.elements.player) { shorts = /short/.test(this.parentElement.href); if ( width / height < 1 ) { vertical = true } else { vertical = false } - if ( !vertical && shorts ){ width = height * 0.6} - if ( vertical && !shorts ){ height = width * 0.6} } + if ( !vertical && shorts ) { width = height * 0.6} + if ( vertical && !shorts ) { height = width * 0.6} } "use strict"; window.open(`${location.protocol}//www.youtube.com/embed/videoseries?autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}&list=${this.dataset.list}`, '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); //~ change focused tab to URL-less popup @@ -224,7 +224,7 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c */ ImprovedTube.playlistPopupUpdate = function () { "use strict"; - if (this.storage.playlist_popup === true){ + if (this.storage.playlist_popup === true) { const playlistID = location.search.match(this.regex.playlist_id)?.[1], playlistIDMini = this.elements.player?.getPlaylistId?.(); diff --git a/js&css/web-accessible/www.youtube.com/shortcuts.js b/js&css/web-accessible/www.youtube.com/shortcuts.js index 0c04088b0..c743907cc 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -447,17 +447,17 @@ ImprovedTube.shortcutDislike = function () { ImprovedTube.shortcutReport = function () { try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} - catch {console.log("'...' failed"); setTimeout(function (){try {document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} + catch {console.log("'...' failed"); setTimeout(function () {try {document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} catch {console.log("'...' failed2")}}, 100) } - setTimeout(function (){try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} + setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} catch {console.log("report failed"); setTimeout(function () {try {document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} catch {console.log("report failed2"); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}}, 800); } }, 200); - setTimeout(function (){try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed"); - setTimeout(function (){try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed2");}}, 1700)}}, 700) + setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed"); + setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed2");}}, 1700)}}, 700) } /*------------------------------------------------------------------------------ 4.7.24 SUBSCRIBE diff --git a/menu/satus.js b/menu/satus.js index 6ab9503f7..f885bbe9a 100644 --- a/menu/satus.js +++ b/menu/satus.js @@ -239,7 +239,7 @@ satus.isset = function (target, is_object) { /*------------------------------------------------------------- # is___(target) --------------------------------------------------------------*/ -satus.isFunction =function (target){return typeof target ==='function';}; +satus.isFunction =function (target) {return typeof target ==='function';}; satus.isArray = Array.isArray; satus.isString = function (t) { return typeof t ==='string'; }; @@ -249,7 +249,7 @@ satus.isElement = function (t) { return (t instanceof Element || t instanceof H satus.isNodeList = function (t) { return t instanceof NodeList; }; satus.isBoolean = function (t) { return (t === false || t === true); }; /*---LOG------------------------------------------------------*/ -satus.log =function (){console.log.apply(null, arguments);}; +satus.log =function () {console.log.apply(null, arguments);}; /*-------------------------------------------------------------- From 270169ff7ab94d6c31d5fb1b3c1fe0427d064056 Mon Sep 17 00:00:00 2001 From: Alan Tan Date: Thu, 4 Jul 2024 23:57:29 +0800 Subject: [PATCH 17/17] Add brace-style check --- background.js | 33 +- eslint.config.mjs | 5 +- js&css/extension/functions.js | 5 +- js&css/extension/init.js | 13 +- .../www.youtube.com/general/general.js | 37 +- .../www.youtube.com/night-mode/night-mode.js | 12 +- js&css/web-accessible/core.js | 27 +- js&css/web-accessible/functions.js | 119 +++-- js&css/web-accessible/init.js | 20 +- .../www.youtube.com/appearance.js | 332 ++++++------ .../web-accessible/www.youtube.com/channel.js | 13 +- .../web-accessible/www.youtube.com/player.js | 475 +++++++++++------- .../www.youtube.com/playlist.js | 43 +- .../www.youtube.com/settings.js | 7 +- .../www.youtube.com/shortcuts.js | 78 ++- menu/index.js | 4 +- menu/satus.js | 62 ++- menu/skeleton-parts/appearance.js | 37 +- menu/skeleton-parts/general.js | 14 +- 19 files changed, 854 insertions(+), 482 deletions(-) diff --git a/background.js b/background.js index 977ff9f00..5e7633916 100644 --- a/background.js +++ b/background.js @@ -95,13 +95,15 @@ chrome.runtime.onInstalled.addListener(function (installed) { }); } else if (installed.reason == 'install') { if (navigator.userAgent.indexOf("Firefox") != -1) { - chrome.storage.local.set({below_player_pip: false})} + chrome.storage.local.set({below_player_pip: false}) + } if (navigator.userAgent.indexOf('Safari') !== -1 && (!/Windows|Chrom/.test(navigator.userAgent) || /Macintosh|iPhone/.test(navigator.userAgent))) { chrome.storage.local.set({below_player_pip: false}) // still needed? (are screenshots broken in Safari?): - chrome.storage.local.set({below_player_screenshot: false})} + chrome.storage.local.set({below_player_screenshot: false}) + } // console.log('Thanks for installing!'); } }); @@ -120,7 +122,9 @@ function getLocale (language, callback) { } else { getLocale('en', callback); } - }).catch(function () { getLocale('en', callback); }); + }).catch(function () { + getLocale('en', callback); + }); getLocale('en', callback); } }).catch(function () { @@ -179,8 +183,12 @@ chrome.runtime.onInstalled.addListener(function (details) { chrome.storage.onChanged.addListener(function (changes) { for (var key in changes) { - if (key === 'language') { updateContextMenu(changes[key].newValue); } - if (key === 'improvedTubeSidebar') { chrome.sidePanel.setPanelBehavior({openPanelOnActionClick: changes[key].newValue}); } + if (key === 'language') { + updateContextMenu(changes[key].newValue); + } + if (key === 'improvedTubeSidebar') { + chrome.sidePanel.setPanelBehavior({openPanelOnActionClick: changes[key].newValue}); + } } }); /*-------------------------------------------------------------- @@ -202,7 +210,9 @@ function tabPrune (callback) { } } callback(); - }, function () { console.log("Error querying Tabs") }); + }, function () { + console.log("Error querying Tabs") + }); }; /*-------------------------------------------------------------- # TAB FOCUS/BLUR @@ -293,14 +303,18 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { top: 20 } - if (tID) {data.tabId = tID;} + if (tID) { + data.tabId = tID; + } chrome.windows.create(data, pw => {}); //append to title? chrome.tabs.onUpdated.addListener(function listener (tabId, changeInfo) { if (tabId === tID && changeInfo.status === 'complete' && !message.title.startsWith("undefined")) { chrome.tabs.onUpdated.removeListener(listener); - chrome.scripting.executeScript({ target: { tabId: tID }, func: () => { document.title = `${message.title} - ImprovedTube`; } }); //manifest3 + chrome.scripting.executeScript({ target: { tabId: tID }, func: () => { + document.title = `${message.title} - ImprovedTube`; + } }); //manifest3 // chrome.tabs.executeScript(tID, {code: `document.title = "${message.title} - ImprovedTube";`}); //manifest2 } }); @@ -327,7 +341,8 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { } } else { console.error('Permission is not granted.'); - }}) + } + }) break } }); diff --git a/eslint.config.mjs b/eslint.config.mjs index 79d954db2..d5ce7fd67 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -37,13 +37,14 @@ export default [...compat.extends("eslint:recommended"), ...compatConfiguration, }, rules: { indent: ["error", "tab", {"SwitchCase": 1}], + "brace-style": "error", "no-empty": ["error", { "allowEmptyCatch": true }], "no-unused-vars": ["error", { "caughtErrors": "none" }], "no-undef": ["off"], "no-trailing-spaces": "warn", "no-multi-spaces": "warn", - "semi-spacing": "error", - "comma-spacing": "error", + "semi-spacing": "warn", + "comma-spacing": "warn", "no-fallthrough": ["error", { "allowEmptyCase": true }], "no-implicit-globals": "error", "no-multiple-empty-lines": ["error", {"max": 1, "maxBOF": 0, "maxEOF": 0}], diff --git a/js&css/extension/functions.js b/js&css/extension/functions.js index cc7ac242e..a3c828437 100644 --- a/js&css/extension/functions.js +++ b/js&css/extension/functions.js @@ -5,4 +5,7 @@ --------------------------------------------------------------*/ extension.functions.getUrlParameter = function (url, parameter) { var match = url.match(new RegExp('(\\?|\\&)' + parameter + '=[^&]+')); - if (match) {return match[0].substr(3);}}; \ No newline at end of file + if (match) { + return match[0].substr(3); + } +}; \ No newline at end of file diff --git a/js&css/extension/init.js b/js&css/extension/init.js index 8020cd839..91d640531 100644 --- a/js&css/extension/init.js +++ b/js&css/extension/init.js @@ -243,6 +243,15 @@ document.addEventListener('it-message-from-youtube', function () { document.addEventListener('it-play', function (event) { var videos = document.querySelectorAll('video'); - try {chrome.runtime.sendMessage({action: 'play'})} - catch (error) {console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } + try { + chrome.runtime.sendMessage({action: 'play'}) + } catch (error) { + console.log(error); setTimeout(function () { + try { + chrome.runtime.sendMessage({action: 'play'}, function (response) { + console.log(response) + } ); + } catch { } + }, 321) + } }); diff --git a/js&css/extension/www.youtube.com/general/general.js b/js&css/extension/www.youtube.com/general/general.js index 374627927..8413b5a6c 100644 --- a/js&css/extension/www.youtube.com/general/general.js +++ b/js&css/extension/www.youtube.com/general/general.js @@ -170,7 +170,9 @@ extension.features.addScrollToTop = function (event) { path.setAttribute('d', 'M13 19V7.8l4.9 5c.4.3 1 .3 1.4 0 .4-.5.4-1.1 0-1.5l-6.6-6.6a1 1 0 0 0-1.4 0l-6.6 6.6a1 1 0 1 0 1.4 1.4L11 7.8V19c0 .6.5 1 1 1s1-.5 1-1z'); svg.appendChild(path); this.addScrollToTop.button.appendChild(svg); - window.addEventListener('scroll', function () { document.body.appendChild(extension.features.addScrollToTop.button); }); + window.addEventListener('scroll', function () { + document.body.appendChild(extension.features.addScrollToTop.button); + }); this.addScrollToTop.button.addEventListener('click', function () { window.scrollTo(0, 0); document.getElementById('it-scroll-to-top')?.remove(); @@ -249,15 +251,30 @@ extension.features.popupWindowButtons = function (event) { target.itPopupWindowButton.addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); - try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch (error) { console.log(error)}; + try { + this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] + } catch (error) { + console.log(error) + }; ytPlayer = document.querySelector("#movie_player"); - if (ytPlayer) {width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} - else { width = innerWidth * 0.4; height = innerHeight * 0.4; } + if (ytPlayer) { + width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65 + } else { + width = innerWidth * 0.4; height = innerHeight * 0.4; + } if (!ytPlayer) { let shorts = /short/.test(this.parentElement.href); - if ( width / height < 1 ) { let vertical = true } else { let vertical = false } - if ( !vertical && shorts ) { width = height * 0.6} - if ( vertical && !shorts ) { height = width * 0.6} + if ( width / height < 1 ) { + let vertical = true + } else { + let vertical = false + } + if ( !vertical && shorts ) { + width = height * 0.6 + } + if ( vertical && !shorts ) { + height = width * 0.6 + } } window.open('https://www.youtube.com/embed/' + this.dataset.id + '?autoplay=' + (extension.storage.get('player_autoplay_disable') ? '0' : '1'), '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); @@ -356,7 +373,8 @@ extension.features.markWatchedVideos = function (anything) { target.itMarkWatchedVideosButton.appendChild(svg); target.itMarkWatchedVideosButton.appendChild(svg2); if (extension.storage.get('watched') && extension.storage.get('watched')[id]) { - target.itMarkWatchedVideosButton.setAttribute('watched', '')}; + target.itMarkWatchedVideosButton.setAttribute('watched', '') + }; target.appendChild(target.itMarkWatchedVideosButton); target.itMarkWatchedVideosButton.addEventListener('click', function (event) { var id = this.dataset.id, @@ -379,7 +397,8 @@ extension.features.markWatchedVideos = function (anything) { chrome.storage.local.set({ watched: extension.storage.get('watched') - });}); + }); + }); } else { var button = target.itMarkWatchedVideosButton; diff --git a/js&css/extension/www.youtube.com/night-mode/night-mode.js b/js&css/extension/www.youtube.com/night-mode/night-mode.js index 084a4e843..d729a0fd4 100644 --- a/js&css/extension/www.youtube.com/night-mode/night-mode.js +++ b/js&css/extension/www.youtube.com/night-mode/night-mode.js @@ -82,10 +82,16 @@ extension.features.bluelight = function () { extension.features.dim = function () { var value = extension.storage.get('dim'); - if (extension.features.schedule() === false) { return false;} + if (extension.features.schedule() === false) { + return false; + } - if (!value) { value = 0;} - if (typeof value !== 'number') {value = Number(value);} + if (!value) { + value = 0; + } + if (typeof value !== 'number') { + value = Number(value); + } if (value !== 0) { if (!this.dim.element) { var element = document.createElement('div'); diff --git a/js&css/web-accessible/core.js b/js&css/web-accessible/core.js index 47d95bf36..b7d4423c8 100644 --- a/js&css/web-accessible/core.js +++ b/js&css/web-accessible/core.js @@ -181,7 +181,8 @@ document.addEventListener('it-message-from-extension', function () { if (ImprovedTube.storage.block_vp9 || ImprovedTube.storage.block_av1 || ImprovedTube.storage.block_h264) { let atlas = {block_vp9:'vp9|vp09', block_h264:'avc1', block_av1:'av01'}, codec = Object.keys(atlas).reduce(function (all, key) { - return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all}, ''); + return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all + }, ''); if (localStorage['it-codec'] != codec) { localStorage['it-codec'] = codec; } @@ -207,7 +208,8 @@ document.addEventListener('it-message-from-extension', function () { if (['block_vp9', 'block_h264', 'block_av1'].includes(message.key)) { let atlas = {block_vp9:'vp9|vp09', block_h264:'avc1', block_av1:'av01'} localStorage['it-codec'] = Object.keys(atlas).reduce(function (all, key) { - return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all}, ''); + return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all + }, ''); if (!localStorage['it-codec']) { localStorage.removeItem('it-codec'); } @@ -246,9 +248,13 @@ document.addEventListener('it-message-from-extension', function () { case 'description': if (ImprovedTube.storage.description === "expanded" || ImprovedTube.storage.description === "classic_expanded") { - try {document.querySelector("#more").click() || document.querySelector("#expand").click();} catch {} + try { + document.querySelector("#more").click() || document.querySelector("#expand").click(); + } catch {} } else if (ImprovedTube.storage.description === "normal" || ImprovedTube.storage.description === "classic") { - try {document.querySelector("#less").click() || document.querySelector("#collapse").click();} catch {} + try { + document.querySelector("#less").click() || document.querySelector("#collapse").click(); + } catch {} } break @@ -282,7 +288,9 @@ document.addEventListener('it-message-from-extension', function () { var button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); if (button && ImprovedTube.elements.ytd_watch.theater === true) { ImprovedTube.elements.ytd_watch.theater = false; - setTimeout(function () { button.click();}, 100); + setTimeout(function () { + button.click(); + }, 100); } } break @@ -396,7 +404,10 @@ document.addEventListener('it-message-from-extension', function () { break case 'playerlistUpNextAutoplay': if (this.storage.playlist_up_next_autoplay !== false) { - if (playlistData.currentIndex != playlistData.localCurrentIndex) { playlistData.currentIndex = playlistData.localCurrentIndex;} } + if (playlistData.currentIndex != playlistData.localCurrentIndex) { + playlistData.currentIndex = playlistData.localCurrentIndex; + } + } break } @@ -404,7 +415,9 @@ document.addEventListener('it-message-from-extension', function () { if (message.key.startsWith('shortcut_')) camelized_key = 'shortcuts'; if (ImprovedTube[camelized_key]) { - try {ImprovedTube[camelized_key]()} catch {}; + try { + ImprovedTube[camelized_key]() + } catch {}; } } else if (message.focus === true && ImprovedTube.elements.player) { ImprovedTube.focus = true; diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index edbcbce7c..0b642913a 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -56,11 +56,22 @@ ImprovedTube.ytElementsHandler = function (node) { if (index === 0) { if (this.storage.playlist_reverse === true) { //can be precise: - try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} - catch {try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} - catch {try {this.elements.playlist.actions = node.parentNode.parentNode;} - catch {try {this.elements.playlist.actions = node.parentNode;} - catch {try {this.elements.playlist.actions = node;} catch {}} + try { + this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode; + } catch { + try { + this.elements.playlist.actions = node.parentNode.parentNode.parentNode; + } catch { + try { + this.elements.playlist.actions = node.parentNode.parentNode; + } catch { + try { + this.elements.playlist.actions = node.parentNode; + } catch { + try { + this.elements.playlist.actions = node; + } catch {} + } } } } @@ -73,11 +84,22 @@ ImprovedTube.ytElementsHandler = function (node) { if (this.storage.playlist_reverse === true) { //can be precise: - try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} - catch {try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} - catch {try {this.elements.playlist.actions = node.parentNode.parentNode;} - catch {try {this.elements.playlist.actions = node.parentNode;} - catch {try {this.elements.playlist.actions = node;} catch {}} + try { + this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode; + } catch { + try { + this.elements.playlist.actions = node.parentNode.parentNode.parentNode; + } catch { + try { + this.elements.playlist.actions = node.parentNode.parentNode; + } catch { + try { + this.elements.playlist.actions = node.parentNode; + } catch { + try { + this.elements.playlist.actions = node; + } catch {} + } } } } @@ -131,8 +153,7 @@ ImprovedTube.ytElementsHandler = function (node) { this.improvedtubeYoutubeIcon(); } - } - else if (name === 'TP-YT-APP-DRAWER') { + } else if (name === 'TP-YT-APP-DRAWER') { if (!this.elements.app_drawer) { this.elements.app_drawer = {start: node.querySelector('div#header'), logo: node.querySelector('a#logo') @@ -227,8 +248,13 @@ ImprovedTube.ytElementsHandler = function (node) { } } else if (document.documentElement.dataset.pageType === 'video') { if (id === 'description-inline-expander' || id === 'description-inner') { - setTimeout(function () {ImprovedTube.expandDescription(node);}, 300); - } else if (id === 'meta') {setTimeout(function () {ImprovedTube.expandDescription(node.querySelector('#more'));}, 200); + setTimeout(function () { + ImprovedTube.expandDescription(node); + }, 300); + } else if (id === 'meta') { + setTimeout(function () { + ImprovedTube.expandDescription(node.querySelector('#more')); + }, 200); } else if (id === 'below') { setTimeout(function () {}, 0); } else if (id === 'panels') { @@ -286,7 +312,9 @@ ImprovedTube.videoPageUpdate = function () { ImprovedTube.upNextAutoplay(); ImprovedTube.playerAutofullscreen(); ImprovedTube.playerSize(); - if (this.storage.player_always_repeat === true) { ImprovedTube.playerRepeat(); }; + if (this.storage.player_always_repeat === true) { + ImprovedTube.playerRepeat(); + }; ImprovedTube.playerScreenshotButton(); ImprovedTube.playerRepeatButton(); ImprovedTube.playerRotateButton(); @@ -343,7 +371,9 @@ ImprovedTube.initPlayer = function () { ImprovedTube.playerQuality(); ImprovedTube.batteryFeatures(); ImprovedTube.playerVolume(); - if (this.storage.player_always_repeat === true) { ImprovedTube.playerRepeat(); } + if (this.storage.player_always_repeat === true) { + ImprovedTube.playerRepeat(); + } ImprovedTube.playerScreenshotButton(); ImprovedTube.playerRepeatButton(); ImprovedTube.playerRotateButton(); @@ -352,8 +382,12 @@ ImprovedTube.initPlayer = function () { ImprovedTube.playerHamburgerButton(); ImprovedTube.playerControls(); ImprovedTube.expandDescription(); - setTimeout(function () {ImprovedTube.forcedTheaterMode();}, 150); - if (location.href.indexOf('/embed/') === -1) { ImprovedTube.miniPlayer(); } + setTimeout(function () { + ImprovedTube.forcedTheaterMode(); + }, 150); + if (location.href.indexOf('/embed/') === -1) { + ImprovedTube.miniPlayer(); + } } }; @@ -376,8 +410,12 @@ ImprovedTube.playerOnTimeUpdate = function () { ImprovedTube.playerQuality(); } - if (ImprovedTube.storage.always_show_progress_bar === true) {ImprovedTube.showProgressBar();} - if (ImprovedTube.storage.player_remaining_duration === true) {ImprovedTube.playerRemainingDuration();} + if (ImprovedTube.storage.always_show_progress_bar === true) { + ImprovedTube.showProgressBar(); + } + if (ImprovedTube.storage.player_remaining_duration === true) { + ImprovedTube.playerRemainingDuration(); + } ImprovedTube.played_time += .5; }, 500); } @@ -389,7 +427,9 @@ ImprovedTube.playerOnTimeUpdate = function () { }; ImprovedTube.playerOnLoadedMetadata = function () { - setTimeout(function () {ImprovedTube.playerSize();}, 100); + setTimeout(function () { + ImprovedTube.playerSize(); + }, 100); }; ImprovedTube.playerOnPause = function (event) { @@ -431,14 +471,18 @@ ImprovedTube.onkeydown = function () { ImprovedTube.onmousedown = function () { window.addEventListener('mousedown', function (event) { if (!ImprovedTube.user_interacted) { - setTimeout(function () {ImprovedTube.user_interacted = true}, 3000); + setTimeout(function () { + ImprovedTube.user_interacted = true + }, 3000); if (ImprovedTube.elements.player && ImprovedTube.elements.player.classList.contains('ad-showing') === false) { var path = event.composedPath(); for (var i = 0, l = path.length; i < l; i++) { if (path[i].className // && path[i].className.indexOf && (/html5-(main-video|video-container)|ytp-play-button/.test(path[i].className)) - ) {ImprovedTube.user_interacted = true;} + ) { + ImprovedTube.user_interacted = true; + } } } } @@ -578,7 +622,8 @@ ImprovedTube.createPlayerButton = function (options) { tooltip.textContent = this.dataset.title; if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)) { - tooltip.style.zIndex = 10001;} // needed for cinema mode + tooltip.style.zIndex = 10001; + } // needed for cinema mode function mouseleave () { tooltip.remove(); @@ -614,8 +659,14 @@ ImprovedTube.createPlayerButton = function (options) { } }; -ImprovedTube.empty = function (element) {for (var i = element.childNodes.length - 1; i > -1; i--) { element.childNodes[i].remove(); }}; -ImprovedTube.isset = function (variable) {return !(typeof variable === 'undefined' || variable === null || variable === 'null');}; +ImprovedTube.empty = function (element) { + for (var i = element.childNodes.length - 1; i > -1; i--) { + element.childNodes[i].remove(); + } +}; +ImprovedTube.isset = function (variable) { + return !(typeof variable === 'undefined' || variable === null || variable === 'null'); +}; ImprovedTube.showStatus = function (value) { if (!this.elements.status) { this.elements.status = document.createElement('div'); @@ -633,17 +684,25 @@ ImprovedTube.showStatus = function (value) { clearTimeout(ImprovedTube.status_timer); } - ImprovedTube.status_timer = setTimeout(function () {ImprovedTube.elements.status.remove();}, 500); + ImprovedTube.status_timer = setTimeout(function () { + ImprovedTube.elements.status.remove(); + }, 500); this.elements.player.appendChild(this.elements.status); }; -ImprovedTube.videoId = function (url = document.URL) {return url.match(ImprovedTube.regex.video_id)[1] || url.searchParams.get('v') || movie_player.getVideoData().video_id}; -ImprovedTube.videoTitle = function () {return document.title?.replace(/\s*-\s*YouTube$/, '') || movie_player.getVideoData().title || document.querySelector('#title > h1 > *')?.textContent}; +ImprovedTube.videoId = function (url = document.URL) { + return url.match(ImprovedTube.regex.video_id)[1] || url.searchParams.get('v') || movie_player.getVideoData().video_id +}; +ImprovedTube.videoTitle = function () { + return document.title?.replace(/\s*-\s*YouTube$/, '') || movie_player.getVideoData().title || document.querySelector('#title > h1 > *')?.textContent +}; // Function to extract and store the number of subscribers ImprovedTube.extractSubscriberCount = function (subscriberCountNode) { - if (!subscriberCountNode) {subscriberCountNode = document.getElementById('owner-sub-count');} + if (!subscriberCountNode) { + subscriberCountNode = document.getElementById('owner-sub-count'); + } if (subscriberCountNode) { // Extract the subscriber count and store it for further use var subscriberCountText = subscriberCountNode.textContent.trim(); diff --git a/js&css/web-accessible/init.js b/js&css/web-accessible/init.js index 628171893..efcfd1fc9 100644 --- a/js&css/web-accessible/init.js +++ b/js&css/web-accessible/init.js @@ -3,7 +3,9 @@ --------------------------------------------------------------*/ ImprovedTube.messages.create(); ImprovedTube.messages.listener(); -if (document.body) { ImprovedTube.childHandler(document.body); } +if (document.body) { + ImprovedTube.childHandler(document.body); +} ImprovedTube.observer = new MutationObserver(function (mutationList) { @@ -105,8 +107,12 @@ ImprovedTube.init = function () { this.onmousedown(); this.youtubeLanguage(); this.myColors(); - if (this.storage.undo_the_new_sidebar === true) {this.undoTheNewSidebar();} - if (this.storage.description === "sidebar") {this.descriptionSidebar();} + if (this.storage.undo_the_new_sidebar === true) { + this.undoTheNewSidebar(); + } + if (this.storage.description === "sidebar") { + this.descriptionSidebar(); + } this.channelCompactTheme(); if (ImprovedTube.elements.player && ImprovedTube.elements.player.setPlaybackRate) { @@ -145,7 +151,9 @@ document.addEventListener('yt-navigate-finish', function () { // if(node.getAttribute('itemprop') === 'uploadDate') {ImprovedTube.uploadDate = node.content;} */ ImprovedTube.pageType(); - if (ImprovedTube.storage.undo_the_new_sidebar) { ImprovedTube.undoTheNewSidebar(); } + if (ImprovedTube.storage.undo_the_new_sidebar) { + ImprovedTube.undoTheNewSidebar(); + } ImprovedTube.commentsSidebar(); if (ImprovedTube.elements.player && ImprovedTube.elements.player.setPlaybackRate) { @@ -174,7 +182,9 @@ window.addEventListener('load', function () { logo: document.querySelector('tp-yt-app-drawer a#logo') } ImprovedTube.improvedtubeYoutubeIcon(); - if (document.documentElement.dataset.pageType === 'video') { ImprovedTube.expandDescription(); } + if (document.documentElement.dataset.pageType === 'video') { + ImprovedTube.expandDescription(); + } if (document.documentElement.dataset.pageType === 'home' && ImprovedTube.storage.youtube_home_page === 'search' ) { document.querySelector('body').style.setProperty('visibility', 'visible', 'important'); ImprovedTube.shortcutGoToSearchBox(); diff --git a/js&css/web-accessible/www.youtube.com/appearance.js b/js&css/web-accessible/www.youtube.com/appearance.js index b4485e10b..a952faf48 100644 --- a/js&css/web-accessible/www.youtube.com/appearance.js +++ b/js&css/web-accessible/www.youtube.com/appearance.js @@ -8,7 +8,9 @@ ImprovedTube.undoTheNewSidebar = function () { yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = false; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments_ep = false; yt.config_.EXPERIMENT_FLAGS.web_watch_rounded_player_large = false; - } catch (error) { console.error("can't undo description on the side", error); } + } catch (error) { + console.error("can't undo description on the side", error); + } } }; @@ -17,7 +19,9 @@ ImprovedTube.descriptionSidebar = function () { yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid = true; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = true; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments_ep = true; - } catch (error) { console.error("tried to move description to the sidebar", error); } + } catch (error) { + console.error("tried to move description to the sidebar", error); + } }; /*------------------------------------------------------------------------------ PLAYER @@ -37,7 +41,9 @@ ImprovedTube.playerSize = function () { style.textContent += "}"; document.body.appendChild(style); - if (document.documentElement.dataset.pageType === 'video') { window.dispatchEvent(new Event('resize')); } + if (document.documentElement.dataset.pageType === 'video') { + window.dispatchEvent(new Event('resize')); + } } }; /*------------------------------------------------------------------------------ @@ -150,104 +156,108 @@ ImprovedTube.playerRemainingDuration = function () { /*------------------------------------------------------------------------------ Comments Sidebar Simple ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebarSimple = function () { if (ImprovedTube.storage.comments_sidebar_simple === true) { - if (window.matchMedia("(min-width: 1599px)").matches) { - document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments"));} - if (window.matchMedia("(max-width: 1598px)").matches) { - document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); - setTimeout(function () { - document.querySelector("#primary-inner").appendChild(document.querySelector("#related"));} - );} -} +ImprovedTube.commentsSidebarSimple = function () { + if (ImprovedTube.storage.comments_sidebar_simple === true) { + if (window.matchMedia("(min-width: 1599px)").matches) { + document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments")); + } + if (window.matchMedia("(max-width: 1598px)").matches) { + document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); + setTimeout(function () { + document.querySelector("#primary-inner").appendChild(document.querySelector("#related")); + } + ); + } + } } /*------------------------------------------------------------------------------ Comments Sidebar ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_sidebar === true) { - const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); - let hasApplied = 0; - if (/watch\?/.test(location.href)) { - sidebar(); - styleScrollbars(); - setGrid(); - applyObserver(); - window.addEventListener("resize", sidebar) - } - - function sidebar () { - resizePlayer(); - if (window.matchMedia("(min-width: 1952px)").matches) { +ImprovedTube.commentsSidebar = function () { + if (ImprovedTube.storage.comments_sidebar === true) { + const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); + let hasApplied = 0; + if (/watch\?/.test(location.href)) { + sidebar(); + styleScrollbars(); + setGrid(); + applyObserver(); + window.addEventListener("resize", sidebar) + } - if (!hasApplied) { - initialSetup() - setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) - } - else if (hasApplied == 2) { //from medium to big size - setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) + function sidebar () { + resizePlayer(); + if (window.matchMedia("(min-width: 1952px)").matches) { + + if (!hasApplied) { + initialSetup() + setTimeout(() => { + document.getElementById("columns").appendChild(document.getElementById("related")) + }) + } else if (hasApplied == 2) { //from medium to big size + setTimeout(() => { + document.getElementById("columns").appendChild(document.getElementById("related")) + }) + } + hasApplied = 1 + } else if (window.matchMedia("(min-width: 1000px)").matches) { + if (!hasApplied) { + initialSetup(); + } else if (hasApplied == 1) { //from big to medium + document.getElementById("primary-inner").appendChild(document.getElementById("related")); + } + hasApplied = 2 + } else { /// <1000 + if (hasApplied == 1) { + document.getElementById("primary-inner").appendChild(document.getElementById("related")); + let comments = document.querySelector("#comments"); + let below = document.getElementById("below"); + below.appendChild(comments); + } else if (hasApplied == 2) { + let comments = document.querySelector("#comments"); + let below = document.getElementById("below"); + below.appendChild(comments); + } + hasApplied = 0; } - hasApplied = 1 } - else if (window.matchMedia("(min-width: 1000px)").matches) { - if (!hasApplied) { - initialSetup(); - } - else if (hasApplied == 1) { //from big to medium - document.getElementById("primary-inner").appendChild(document.getElementById("related")); - } - hasApplied = 2 + function setGrid () { + let checkParentInterval = setInterval(() => { + container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; + if (container) { + clearInterval(checkParentInterval); + container.style.display = "flex"; + container.style.flexWrap = "wrap"; + container.style.flexDirection = "row"; + } + }, 250); } - else { /// <1000 - if (hasApplied == 1) { - document.getElementById("primary-inner").appendChild(document.getElementById("related")); - let comments = document.querySelector("#comments"); - let below = document.getElementById("below"); - below.appendChild(comments); - } - else if (hasApplied == 2) { - let comments = document.querySelector("#comments"); - let below = document.getElementById("below"); - below.appendChild(comments); - } - hasApplied = 0; + function initialSetup () { + let secondaryInner = document.getElementById("secondary-inner"); + let primaryInner = document.getElementById("primary-inner"); + let comments = document.querySelector("#comments"); + setTimeout(() => { + primaryInner.appendChild(document.getElementById("panels")); + primaryInner.appendChild(document.getElementById("related")) + secondaryInner.appendChild(document.getElementById("chat-template")); + secondaryInner.appendChild(comments); + }) } - } - function setGrid () { - let checkParentInterval = setInterval(() => { - container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; - if (container) { - clearInterval(checkParentInterval); - container.style.display = "flex"; - container.style.flexWrap = "wrap"; - container.style.flexDirection = "row"; - } - }, 250); - } - function initialSetup () { - let secondaryInner = document.getElementById("secondary-inner"); - let primaryInner = document.getElementById("primary-inner"); - let comments = document.querySelector("#comments"); - setTimeout(() => { - primaryInner.appendChild(document.getElementById("panels")); - primaryInner.appendChild(document.getElementById("related")) - secondaryInner.appendChild(document.getElementById("chat-template")); - secondaryInner.appendChild(comments); - }) - } - function resizePlayer () { - const width = video.offsetWidth + 24; - const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); - document.getElementById("primary").style.width = `${width}px`; - player.style.width = `${width}px`; - } - function styleScrollbars () { - if (!navigator.userAgent.toLowerCase().includes("mac")) { - let color, colorHover - const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; - if (isDarkMode) [color, colorHover] = ["#616161", "#909090"]; - else [color, colorHover] = ["#aaaaaa", "#717171"]; - const style = document.createElement("style"); - if (ImprovedTube.storage.comments_sidebar_scrollbars === true) { - const cssRule = ` + function resizePlayer () { + const width = video.offsetWidth + 24; + const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); + document.getElementById("primary").style.width = `${width}px`; + player.style.width = `${width}px`; + } + function styleScrollbars () { + if (!navigator.userAgent.toLowerCase().includes("mac")) { + let color, colorHover + const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; + if (isDarkMode) [color, colorHover] = ["#616161", "#909090"]; + else [color, colorHover] = ["#aaaaaa", "#717171"]; + const style = document.createElement("style"); + if (ImprovedTube.storage.comments_sidebar_scrollbars === true) { + const cssRule = ` #primary, #secondary { overflow: overlay !important; } @@ -268,9 +278,9 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s ::-webkit-scrollbar-thumb:hover{ background-color: ${colorHover}; }`; - style.appendChild(document.createTextNode(cssRule)); - } - else { const cssRule = ` + style.appendChild(document.createTextNode(cssRule)); + } else { + const cssRule = ` #primary, #secondary { overflow: overlay !important; } @@ -279,26 +289,26 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s width: 0px; height: 0px; }`; - style.appendChild(document.createTextNode(cssRule)); + style.appendChild(document.createTextNode(cssRule)); + } + document.head.appendChild(style); } - document.head.appendChild(style); + } + function applyObserver () { + const debouncedResizePlayer = debounce(resizePlayer, 200); + const resizeObserver = new ResizeObserver(debouncedResizePlayer); + resizeObserver.observe(video); + } + function debounce (callback, delay) { + let timerId; + return function (...args) { + clearTimeout(timerId); + timerId = setTimeout(() => { + callback.apply(this, args); + }, delay); + }; } } - function applyObserver () { - const debouncedResizePlayer = debounce(resizePlayer, 200); - const resizeObserver = new ResizeObserver(debouncedResizePlayer); - resizeObserver.observe(video); - } - function debounce (callback, delay) { - let timerId; - return function (...args) { - clearTimeout(timerId); - timerId = setTimeout(() => { - callback.apply(this, args); - }, delay); - }; - } -} } /*------------------------------------------------------------------------------ SIDEBAR @@ -306,19 +316,27 @@ ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_s /*---------------------------------------------------------------- TRANSCRIPT --------------------------------------------------------------*/ -ImprovedTube.transcript = function (el) { if (ImprovedTube.storage.transcript === true) { - el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility');} } +ImprovedTube.transcript = function (el) { + if (ImprovedTube.storage.transcript === true) { + el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility'); + } +} /*---------------------------------------------------------------- CHAPTERS --------------------------------------------------------------*/ -ImprovedTube.chapters = function (el) { if (ImprovedTube.storage.chapters === true) { - el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility');} } +ImprovedTube.chapters = function (el) { + if (ImprovedTube.storage.chapters === true) { + el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility'); + } +} /*------------------------------------------------------------------------------ LIVECHAT ------------------------------------------------------------------------------*/ ImprovedTube.livechat = function () { if (this.storage.livechat === "collapsed") { - if (typeof isCollapsed === 'undefined') { var isCollapsed = false; } + if (typeof isCollapsed === 'undefined') { + var isCollapsed = false; + } if (ImprovedTube.elements.livechat && !isCollapsed) { ImprovedTube.elements.livechat.button.click(); isCollapsed = true @@ -337,7 +355,9 @@ ImprovedTube.livechat = function () { EXTRA BUTTONS BELOW THE PLAYER ------------------------------------------------------------------------------*/ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { - if (window.self !== window.top) { return false; } + if (window.self !== window.top) { + return false; + } if (document.documentElement.dataset.pageType === 'video') { var section = document.querySelector('#subscribe-button'); @@ -350,7 +370,9 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { var button = document.createElement('button'), svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - var transparentOrOn = .5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } + var transparentOrOn = .5; if (this.storage.player_always_repeat === true ) { + transparentOrOn = 1; + } button.className = 'improvedtube-player-button'; button.id = 'it-below-player-loop'; button.dataset.tooltip = 'Loop'; @@ -394,7 +416,9 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { button.onclick = function () { var video = document.querySelector('#movie_player video'); - if (video) {video.requestPictureInPicture();} + if (video) { + video.requestPictureInPicture(); + } }; svg.appendChild(path); button.appendChild(svg); @@ -425,14 +449,29 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { ------------------------------------------------------------------------------*/ ImprovedTube.expandDescription = function (el) { if (this.storage.description === "expanded" || this.storage.description === "classic_expanded") { - if (el) {el.click(); setTimeout(function () {ImprovedTube.elements.player.focus();}, 1200); } - else { var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} + if (el) { + el.click(); setTimeout(function () { + ImprovedTube.elements.player.focus(); + }, 1200); + } else { + var tries = 0; var intervalMs = 210; + if (location.href.indexOf('/watch?') !== -1) { + var maxTries = 10; + } else { + var maxTries = 0; + } // ...except when it is an embedded player? var waitForDescription = setInterval(() => { if (++tries >= maxTries) { el = document.querySelector('#description-inline-expander') - if ( el) { el.click(); setTimeout(function () {ImprovedTube.elements.player.focus(); }, 1200); clearInterval(waitForDescription); } - intervalMs *= 1.11; }}, intervalMs); + if ( el) { + el.click(); setTimeout(function () { + ImprovedTube.elements.player.focus(); + }, 1200); clearInterval(waitForDescription); + } + intervalMs *= 1.11; + } + }, intervalMs); } } } @@ -453,22 +492,35 @@ ImprovedTube.expandDescription = function (el) { /*-------------------------------------------------------------- DAY OF WEEK --------------------------------------------------------------*/ -ImprovedTube.dayOfWeek = function () { if (this.storage.day_of_week === true) { - var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; - setTimeout(function () { - var videoDate; try { videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate } //YouTube related video or internal link? - catch { try { videoDate = document.querySelector("[itemprop=datePublished]").content;} catch { } } //..no? must be new session? - var tempDate = new Date(videoDate); - var element = document.querySelector(".ytd-day-of-week"); - if (!element) { - var label = document.createElement("span"); - label.textContent = days[tempDate.getDay() + 1] + ' '; - label.className = "ytd-day-of-week"; - //update please: - try {document.querySelector("#info span:nth-child(2)")?.append(label);} catch { try {document.querySelector("#info #info-strings yt-formatted-string")?.append(label);} catch {}} - } // else { element.textContent = days[tempDate.getDay() + 1] + ", "; } - }, 4321); -} +ImprovedTube.dayOfWeek = function () { + if (this.storage.day_of_week === true) { + var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; + setTimeout(function () { + var videoDate; try { + videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate + } //YouTube related video or internal link? + catch { + try { + videoDate = document.querySelector("[itemprop=datePublished]").content; + } catch { } + } //..no? must be new session? + var tempDate = new Date(videoDate); + var element = document.querySelector(".ytd-day-of-week"); + if (!element) { + var label = document.createElement("span"); + label.textContent = days[tempDate.getDay() + 1] + ' '; + label.className = "ytd-day-of-week"; + //update please: + try { + document.querySelector("#info span:nth-child(2)")?.append(label); + } catch { + try { + document.querySelector("#info #info-strings yt-formatted-string")?.append(label); + } catch {} + } + } // else { element.textContent = days[tempDate.getDay() + 1] + ", "; } + }, 4321); + } }; /*------------------------------------------------------------------------------ HOW LONG AGO THE VIDEO WAS UPLOADED diff --git a/js&css/web-accessible/www.youtube.com/channel.js b/js&css/web-accessible/www.youtube.com/channel.js index f341886eb..a595ae94c 100644 --- a/js&css/web-accessible/www.youtube.com/channel.js +++ b/js&css/web-accessible/www.youtube.com/channel.js @@ -59,10 +59,12 @@ ImprovedTube.channelCompactTheme = function () { compact.hasApplied = true initialLoad(); document.querySelector("#sections #items") ? styleWithListeners() : styleWithInterval(); - } - else if (compact.hasApplied) { //cleanup - try {clearInterval(compact.listener)} - catch (err) {console.log("ERR: We couldn't clear listener. Reload page")} + } else if (compact.hasApplied) { //cleanup + try { + clearInterval(compact.listener) + } catch (err) { + console.log("ERR: We couldn't clear listener. Reload page") + } if (compact.eventHandlerFns.length) removeListeners(); if (compact.styles.length) removeStyles() compact = {} @@ -92,8 +94,7 @@ ImprovedTube.channelCompactTheme = function () { if (!isCompact) { sub.style.display = "none" isCompact = true - } - else { + } else { sub.style.display = "" isCompact = false } diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index 113f2a215..db4417071 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -7,7 +7,9 @@ ImprovedTube.autoplayDisable = function (videoElement) { || this.storage.channel_trailer_autoplay === false) { const player = this.elements.player || videoElement.closest('.html5-video-player') || videoElement.closest('#movie_player'); // #movie_player: outdated since 2024? - if (this.video_url !== location.href) { this.user_interacted = false; } + if (this.video_url !== location.href) { + this.user_interacted = false; + } // if (no user clicks) and (no ads playing) and // ( there is a player and ( (it is not in a playlist and auto play is off ) or ( playlist auto play is off and in a playlist ) ) ) or (if we are in a channel and the channel trailer autoplay is off) ) @@ -26,7 +28,11 @@ ImprovedTube.autoplayDisable = function (videoElement) { || (this.storage.channel_trailer_autoplay === false && this.regex.channel.test(location.href)))) { setTimeout(function () { - try { player.pauseVideo(); } catch (error) { console.log("autoplayDisable: Pausing"); videoElement.pause(); } + try { + player.pauseVideo(); + } catch (error) { + console.log("autoplayDisable: Pausing"); videoElement.pause(); + } }); } else { document.dispatchEvent(new CustomEvent('it-play')); @@ -46,7 +52,9 @@ ImprovedTube.forcedPlayVideoFromTheBeginning = function () { if (player && video && this.storage.forced_play_video_from_the_beginning && location.pathname == '/watch') { player.seekTo(0); // restore previous paused state - if (paused) { player.pauseVideo(); } + if (paused) { + player.pauseVideo(); + } } }; /*------------------------------------------------------------------------------ @@ -111,53 +119,76 @@ ImprovedTube.playbackSpeed = function (newSpeed) { /*------------------------------------------------------------------------------ FORCED PLAYBACK SPEED ------------------------------------------------------------------------------*/ -ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_playback_speed === true) { - var player = this.elements.player, - video = player.querySelector('video'), - option = this.storage.player_playback_speed; - if (this.isset(option) === false) { option = 1; } - else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) ) - { console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; } - if ( !player.getVideoData().isLive || player.getVideoData().isLive === false) - { player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl - if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true) +ImprovedTube.playerPlaybackSpeed = function () { + if (this.storage.player_forced_playback_speed === true) { + var player = this.elements.player, + video = player.querySelector('video'), + option = this.storage.player_playback_speed; + if (this.isset(option) === false) { + option = 1; + } else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) ) { + console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; + } + if ( !player.getVideoData().isLive || player.getVideoData().isLive === false) { + player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl + if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true) && option !== 1) { - ImprovedTube.speedException = function () { - if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education') - {player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return;} - if (this.storage.player_force_speed_on_music === true) - { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); - return;} - if (DATA.keywords && !keywords) { keywords = DATA.keywords.join(', ') || ''; } - if (keywords === 'video, sharing, camera phone, video phone, free, upload') { keywords = ''; } - var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i; - var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i; - var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i"); - var musicRegexMatch = musicIdentifiersTitle.test(DATA.title); - if (!musicRegexMatch) { - var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i; - var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i"); + ImprovedTube.speedException = function () { + if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education') { + player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return; + } + if (this.storage.player_force_speed_on_music === true) { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); + return; + } + if (DATA.keywords && !keywords) { + keywords = DATA.keywords.join(', ') || ''; + } + if (keywords === 'video, sharing, camera phone, video phone, free, upload') { + keywords = ''; + } + var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i; + var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i; + var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i"); + var musicRegexMatch = musicIdentifiersTitle.test(DATA.title); + if (!musicRegexMatch) { + var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i; + var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i"); keywordsAmount = 1 + ((keywords || '').match(/,/) || []).length; - if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) { - musicRegexMatch = true}} - notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); - // (Tags/keywords shouldnt lie & very few songs titles might have these words) - if (DATA.duration) { - function parseDuration (duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); - return h * 3600 + m * 60 + s; } - DATA.lengthSeconds = parseDuration(DATA.duration); } - function testSongDuration (s, ytMusic) { - if (135 <= s && s <= 260) {return 'veryCommon';} - if (105 <= s && s <= 420) {return 'common';} - if (420 <= s && s <= 720) {return 'long';} - if (45 <= s && s <= 105) {return 'short';} - if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) {return 'multiple';} - //does Youtube ever show more than 10 songs below the description? - } - var songDurationType = testSongDuration(DATA.lengthSeconds); - console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType); - // check if the video is PROBABLY MUSIC: - if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon')) + if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) { + musicRegexMatch = true + } + } + notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); + // (Tags/keywords shouldnt lie & very few songs titles might have these words) + if (DATA.duration) { + function parseDuration (duration) { + const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); + return h * 3600 + m * 60 + s; + } + DATA.lengthSeconds = parseDuration(DATA.duration); + } + function testSongDuration (s, ytMusic) { + if (135 <= s && s <= 260) { + return 'veryCommon'; + } + if (105 <= s && s <= 420) { + return 'common'; + } + if (420 <= s && s <= 720) { + return 'long'; + } + if (45 <= s && s <= 105) { + return 'short'; + } + if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) { + return 'multiple'; + } + //does Youtube ever show more than 10 songs below the description? + } + var songDurationType = testSongDuration(DATA.lengthSeconds); + console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType); + // check if the video is PROBABLY MUSIC: + if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon')) || ( musicRegexMatch && !notMusicRegexMatch && (typeof songDurationType !== 'undefined' || (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords) && 1000 <= DATA.lengthSeconds )) ) // && 1150 <= DATA.lengthSeconds <= 5000 @@ -166,74 +197,123 @@ ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_ && 1000 <= DATA.lengthSeconds )) ) // && DATA.lengthSeconds <= 5000 || (amountOfSongs && testSongDuration(DATA.lengthSeconds, amountOfSongs ) !== 'undefined') // || location.href.indexOf('music.') !== -1 // (=currently we are only running on www.youtube.com anyways) - ) { player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); } - else { // Now this video might rarely be music + ) { + player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); + } else { // Now this video might rarely be music // - however we can make extra-sure after waiting for the video descripion to load... (#1539) - var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} - // ...except when it is an embedded player? - var waitForDescription = setInterval(() => { - if (++tries >= maxTries) { - subtitle = document.querySelector('#title + #subtitle:last-of-type') - if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs) + var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) { + var maxTries = 10; + } else { + var maxTries = 0; + } + // ...except when it is an embedded player? + var waitForDescription = setInterval(() => { + if (++tries >= maxTries) { + subtitle = document.querySelector('#title + #subtitle:last-of-type') + if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs) && typeof testSongDuration(DATA.lengthSeconds, Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) ) !== 'undefined' ) // resonable duration - {player.setPlaybackRate(1); video.playbackRate = 1; console.log("...but YouTube shows music below the description!"); clearInterval(waitForDescription); } - intervalMs *= 1.11; }}, intervalMs); - window.addEventListener('load', () => { setTimeout(() => { clearInterval(waitForDescription); }, 1234); }); + { + player.setPlaybackRate(1); video.playbackRate = 1; console.log("...but YouTube shows music below the description!"); clearInterval(waitForDescription); + } + intervalMs *= 1.11; + } + }, intervalMs); + window.addEventListener('load', () => { + setTimeout(() => { + clearInterval(waitForDescription); + }, 1234); + }); + } } - } - //DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere) - DATA = {}; - defaultKeywords = "video,sharing,camera,phone,video phone,free,upload"; - DATA.keywords = false; keywords = false; amountOfSongs = false; - DATA.videoID = ImprovedTube.videoId() || false; - ImprovedTube.fetchDOMData = function () { - // if (history.length > 1 && history.state.endpoint.watchEndpoint) { - try { DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name;} - catch { DATA.genre = false; DATA.keywords = false; DATA.lengthSeconds = false; + //DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere) + DATA = {}; + defaultKeywords = "video,sharing,camera,phone,video phone,free,upload"; + DATA.keywords = false; keywords = false; amountOfSongs = false; + DATA.videoID = ImprovedTube.videoId() || false; + ImprovedTube.fetchDOMData = function () { + // if (history.length > 1 && history.state.endpoint.watchEndpoint) { try { - DATA.title = document.getElementsByTagName('meta')?.title?.content || false; - DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; - DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; - } catch {}} if ( DATA.title === ImprovedTube.videoTitle() ) - { keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if (!keywords) {keyword=''} ImprovedTube.speedException(); } - else { keywords = ''; (async function () { try { const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`); - - const htmlContent = await response.text(); - const metaRegex = /]+name=["'](keywords|genre|duration)["'][^>]+content=["']([^"']+)["'][^>]*>/gi; - let match; while ((match = metaRegex.exec(htmlContent)) !== null) { - const [, property, value] = match; - if (property === 'keywords') { keywords = value;} else {DATA[property] = value;} + DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name; + } catch { + DATA.genre = false; DATA.keywords = false; DATA.lengthSeconds = false; + try { + DATA.title = document.getElementsByTagName('meta')?.title?.content || false; + DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; + DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; + } catch {} + } if ( DATA.title === ImprovedTube.videoTitle() ) { + keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if (!keywords) { + keyword='' + } ImprovedTube.speedException(); + } else { + keywords = ''; (async function () { + try { + const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`); + + const htmlContent = await response.text(); + const metaRegex = /]+name=["'](keywords|genre|duration)["'][^>]+content=["']([^"']+)["'][^>]*>/gi; + let match; while ((match = metaRegex.exec(htmlContent)) !== null) { + const [, property, value] = match; + if (property === 'keywords') { + keywords = value; + } else { + DATA[property] = value; + } + } + amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false; + if (keywords) { + ImprovedTube.speedException(); + } + } catch (error) { + console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; + } + })(); } - amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false; - if (keywords) { ImprovedTube.speedException(); } - } catch (error) { console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; } - })(); - } - }; - if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { ImprovedTube.fetchDOMData();} - else { + }; + if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { + ImprovedTube.fetchDOMData(); + } else { //Invidious instances. Should be updated automatically!... - const invidiousInstances = ['invidious.fdn.fr', 'inv.tux.pizza', 'invidious.flokinet.to', 'invidious.protokolla.fi', 'invidious.private.coffee', 'yt.artemislena.eu', 'invidious.perennialte.ch', 'invidious.materialio.us', 'iv.datura.network']; - function getRandomInvidiousInstance () { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} + const invidiousInstances = ['invidious.fdn.fr', 'inv.tux.pizza', 'invidious.flokinet.to', 'invidious.protokolla.fi', 'invidious.private.coffee', 'yt.artemislena.eu', 'invidious.perennialte.ch', 'invidious.materialio.us', 'iv.datura.network']; + function getRandomInvidiousInstance () { + return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)]; + } - (async function () { let retries = 4; let invidiousFetched = false; - async function fetchInvidiousData () { - try {const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); + (async function () { + let retries = 4; let invidiousFetched = false; + async function fetchInvidiousData () { + try { + const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); DATA = await response.json(); - if (DATA.genre && DATA.title && DATA.keywords && DATA.lengthSeconds) { if (DATA.keywords.toString() === defaultKeywords ) {DATA.keywords = ''} - ImprovedTube.speedException(); invidiousFetched = true; } - } catch (error) { console.error('Error: Invidious API: ', error); } - } - while (retries > 0 && !invidiousFetched) { await fetchInvidiousData(); - if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; } } - if (!invidiousFetched) { if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} - else { ImprovedTube.fetchDOMData();} } - })(); - } - } // else { } + if (DATA.genre && DATA.title && DATA.keywords && DATA.lengthSeconds) { + if (DATA.keywords.toString() === defaultKeywords ) { + DATA.keywords = '' + } + ImprovedTube.speedException(); invidiousFetched = true; + } + } catch (error) { + console.error('Error: Invidious API: ', error); + } + } + while (retries > 0 && !invidiousFetched) { + await fetchInvidiousData(); + if (!invidiousFetched) { + await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; + } + } + if (!invidiousFetched) { + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData()) + } else { + ImprovedTube.fetchDOMData(); + } + } + })(); + } + } // else { } + } } } -} /*------------------------------------------------------------------------------ SUBTITLES ------------------------------------------------------------------------------*/ @@ -248,7 +328,9 @@ ImprovedTube.playerSubtitles = function () { break case 'disabled': - if (player.isSubtitlesOn()) { player.toggleSubtitles(); } + if (player.isSubtitlesOn()) { + player.toggleSubtitles(); + } break } } @@ -268,7 +350,9 @@ ImprovedTube.subtitlesLanguage = function () { subtitlesState = player.isSubtitlesOn(); player.setOption('captions', 'track', matchedTrack); // setOption forces Subtitles ON, restore state from before calling it. - if (!subtitlesState) { player.toggleSubtitles(); } + if (!subtitlesState) { + player.toggleSubtitles(); + } } } }; @@ -548,7 +632,9 @@ ImprovedTube.playerVolume = function () { this.audioContextSource.connect(this.audioContextGain); this.audioContextGain.connect(this.audioContext.destination) } - if (this.elements.player.getVolume() !== 100) { this.elements.player.setVolume(100);} + if (this.elements.player.getVolume() !== 100) { + this.elements.player.setVolume(100); + } this.audioContextGain.gain.value = volume / 100; } } @@ -606,7 +692,9 @@ ImprovedTube.screenshot = function () { if (ImprovedTube.storage.embed_subtitle != false) { let captionElements = document.querySelectorAll('.captions-text .ytp-caption-segment'); - captionElements.forEach(function (caption) {subText += caption.textContent.trim() + ' ';}); + captionElements.forEach(function (caption) { + subText += caption.textContent.trim() + ' '; + }); ImprovedTube.renderSubtitle(ctx, captionElements); } @@ -619,7 +707,9 @@ ImprovedTube.screenshot = function () { 'image/png': blob }) ]) - .then(function () { console.log("ImprovedTube: Screeeeeeenshot tada!"); }) + .then(function () { + console.log("ImprovedTube: Screeeeeeenshot tada!"); + }) .catch(function (error) { console.log('ImprovedTube screenshot: ', error); alert('ImprovedTube Screenshot to Clipboard error. Details in Debug Console.'); @@ -700,7 +790,9 @@ ImprovedTube.playerRepeatButton = function () { svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z'); svg.appendChild(path); - var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } + var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { + transparentOrOn = 1; + } this.createPlayerButton({ id: 'it-repeat-button', child: svg, @@ -859,8 +951,7 @@ ImprovedTube.playerCinemaModeButton = function () { player.style.zIndex = 1; svg.parentNode.style.opacity = 0.64; svg.parentNode.style.zIndex = 1; - } - else { + } else { player.style.zIndex = 10000; svg.parentNode.style.opacity = 1; } @@ -918,55 +1009,56 @@ ImprovedTube.playerCinemaModeEnable = function () { /*------------------------------------------------------------------------------ HAMBURGER MENU ------------------------------------------------------------------------------*/ -ImprovedTube.playerHamburgerButton = function () { if (this.storage.player_hamburger_button === true) { - const videoPlayer = document.querySelector('.html5-video-player'); +ImprovedTube.playerHamburgerButton = function () { + if (this.storage.player_hamburger_button === true) { + const videoPlayer = document.querySelector('.html5-video-player'); - if (!videoPlayer) { - return; - } + if (!videoPlayer) { + return; + } - const controlsContainer = videoPlayer.querySelector('.ytp-right-controls'); + const controlsContainer = videoPlayer.querySelector('.ytp-right-controls'); - if (!controlsContainer) { - return; - } + if (!controlsContainer) { + return; + } - let hamburgerMenu = document.querySelector('.custom-hamburger-menu'); - if (!hamburgerMenu) { - hamburgerMenu = document.createElement('div'); - hamburgerMenu.className = 'custom-hamburger-menu'; - hamburgerMenu.style.position = 'absolute'; - hamburgerMenu.style.right = '0'; - hamburgerMenu.style.marginTop = '8px'; - hamburgerMenu.style.cursor = 'pointer'; + let hamburgerMenu = document.querySelector('.custom-hamburger-menu'); + if (!hamburgerMenu) { + hamburgerMenu = document.createElement('div'); + hamburgerMenu.className = 'custom-hamburger-menu'; + hamburgerMenu.style.position = 'absolute'; + hamburgerMenu.style.right = '0'; + hamburgerMenu.style.marginTop = '8px'; + hamburgerMenu.style.cursor = 'pointer'; - const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - svg.setAttribute('style', 'width: 32px; height: 32px;'); + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + svg.setAttribute('style', 'width: 32px; height: 32px;'); - const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z'); - path.setAttributeNS(null, 'fill', 'white'); - - svg.appendChild(path); - hamburgerMenu.appendChild(svg); + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z'); + path.setAttributeNS(null, 'fill', 'white'); - controlsContainer.style.paddingRight = '40px'; - controlsContainer.parentNode.appendChild(hamburgerMenu); + svg.appendChild(path); + hamburgerMenu.appendChild(svg); - let controlsVisible = true; - controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; - controlsVisible = false; + controlsContainer.style.paddingRight = '40px'; + controlsContainer.parentNode.appendChild(hamburgerMenu); - hamburgerMenu.addEventListener('click', function () { + let controlsVisible = true; controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; - controlsVisible = !controlsVisible; + controlsVisible = false; - // Change the opacity of hamburgerMenu based on controls visibility - hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65'; - }); + hamburgerMenu.addEventListener('click', function () { + controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; + controlsVisible = !controlsVisible; + + // Change the opacity of hamburgerMenu based on controls visibility + hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65'; + }); + } } -} }; /*------------------------------------------------------------------------------ POPUP PLAYER @@ -1419,61 +1511,62 @@ ImprovedTube.miniPlayer = function () { /*------------------------------------------------------------------------------ CUSTOM PAUSE FUNCTIONS ------------------------------------------------------------------------------*/ -ImprovedTube.pauseWhileTypingOnYoutube = function () { if (ImprovedTube.storage.pause_while_typing_on_youtube === true) { - var timeoutId; // Declare a variable to hold the timeout ID +ImprovedTube.pauseWhileTypingOnYoutube = function () { + if (ImprovedTube.storage.pause_while_typing_on_youtube === true) { + var timeoutId; // Declare a variable to hold the timeout ID - // Add event listener to the whole document - document.addEventListener('keydown', function (e) { + // Add event listener to the whole document + document.addEventListener('keydown', function (e) { // Check on the storage for pause_while_typing_on_youtube_storage is false - // If player is NOT in the viewport, return - if (!isPlayerInViewport()) { - return; - } + // If player is NOT in the viewport, return + if (!isPlayerInViewport()) { + return; + } - var player = ImprovedTube.elements.player; + var player = ImprovedTube.elements.player; - if (player) { - if ( - (/^[a-z0-9]$/i.test(e.key) || e.key === "Backspace") && + if (player) { + if ( + (/^[a-z0-9]$/i.test(e.key) || e.key === "Backspace") && !(e.ctrlKey && (e.key === "c" || e.key === "x" || e.key === "a")) && - ( document.activeElement.tagName === "INPUT" || document.activeElement.tagName === "TEXTAREA" || document.activeElement.tagName === "DIV" )) - { + ( document.activeElement.tagName === "INPUT" || document.activeElement.tagName === "TEXTAREA" || document.activeElement.tagName === "DIV" )) { // Pause the video // Check if player is paused - if (!player.paused) { - player.pauseVideo(); - } + if (!player.paused) { + player.pauseVideo(); + } - // Clear any existing timeout - if (timeoutId) { - clearTimeout(timeoutId); - } + // Clear any existing timeout + if (timeoutId) { + clearTimeout(timeoutId); + } - // Set a new timeout to play the video after 1 second - timeoutId = setTimeout(function () { - player.playVideo(); - }, 2000); // 2000 milliseconds = 2 seconds + // Set a new timeout to play the video after 1 second + timeoutId = setTimeout(function () { + player.playVideo(); + }, 2000); // 2000 milliseconds = 2 seconds + } } - } - }); + }); - function isPlayerInViewport () { - var player = ImprovedTube.elements.player; - if (player) { - var rect = player.getBoundingClientRect(); - var windowHeight = (window.innerHeight || document.documentElement.clientHeight); - var windowWidth = (window.innerWidth || document.documentElement.clientWidth); + function isPlayerInViewport () { + var player = ImprovedTube.elements.player; + if (player) { + var rect = player.getBoundingClientRect(); + var windowHeight = (window.innerHeight || document.documentElement.clientHeight); + var windowWidth = (window.innerWidth || document.documentElement.clientWidth); - // Check if the player is in the viewport - return ( - rect.top != 0 && + // Check if the player is in the viewport + return ( + rect.top != 0 && rect.left != 0 && rect.bottom <= windowHeight && rect.right <= windowWidth - ); + ); + } + return false; } - return false; - } -}}; + } +}; diff --git a/js&css/web-accessible/www.youtube.com/playlist.js b/js&css/web-accessible/www.youtube.com/playlist.js index 291b595fd..3b3aa91f1 100644 --- a/js&css/web-accessible/www.youtube.com/playlist.js +++ b/js&css/web-accessible/www.youtube.com/playlist.js @@ -4,15 +4,16 @@ /*------------------------------------------------------------------------------ 4.5.1 UP NEXT AUTOPLAY ------------------------------------------------------------------------------*/ -ImprovedTube.playlistUpNextAutoplay = function () { if (this.storage.playlist_up_next_autoplay === false) { - const playlistData = this.elements.ytd_watch?.playlistData; - if (this.getParam(location.href, 'list') && playlistData +ImprovedTube.playlistUpNextAutoplay = function () { + if (this.storage.playlist_up_next_autoplay === false) { + const playlistData = this.elements.ytd_watch?.playlistData; + if (this.getParam(location.href, 'list') && playlistData && playlistData.currentIndex && playlistData.totalVideos && playlistData.localCurrentIndex) { - playlistData.currentIndex = playlistData.totalVideos; + playlistData.currentIndex = playlistData.totalVideos; + } } -} }; /*------------------------------------------------------------------------------ 4.5.2 REVERSE @@ -102,8 +103,9 @@ ImprovedTube.playlistRepeat = function () { && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Loop video' && button.querySelector("#tooltip")?.textContent !== 'Turn off loop' && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Turn off loop' - ) - { button.click(); } + ) { + button.click(); + } }, 10000); } }; @@ -120,8 +122,9 @@ ImprovedTube.playlistShuffle = function () { option = ImprovedTube.storage.playlist_shuffle; button = document.querySelector('#playlist-actions #playlist-action-menu ytd-toggle-button-renderer'); if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M18.1') - ) ) - { button.click(); } + ) ) { + button.click(); + } }, 10000); } }; @@ -187,9 +190,18 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c let height = ImprovedTube.elements.player.offsetHeight * 0.7 ?? innerHeight * 0.45; if (!ImprovedTube.elements.player) { shorts = /short/.test(this.parentElement.href); - if ( width / height < 1 ) { vertical = true } else { vertical = false } - if ( !vertical && shorts ) { width = height * 0.6} - if ( vertical && !shorts ) { height = width * 0.6} } + if ( width / height < 1 ) { + vertical = true + } else { + vertical = false + } + if ( !vertical && shorts ) { + width = height * 0.6 + } + if ( vertical && !shorts ) { + height = width * 0.6 + } + } "use strict"; window.open(`${location.protocol}//www.youtube.com/embed/videoseries?autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}&list=${this.dataset.list}`, '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); //~ change focused tab to URL-less popup @@ -246,5 +258,8 @@ ImprovedTube.playlistPopupUpdate = function () { if (panelItemButtons == null) this.elements.buttons['it-popup-playlist-button-panel'] = null; else panelItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-panel'] = this.playlistPopupCreateButton(playlistID, true, true)); } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-panel'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-panel'].dataset.list = playlistID; - } catch (error) { console.error("Error appending playlist button panel:", error);} - }}; + } catch (error) { + console.error("Error appending playlist button panel:", error); + } + } +}; diff --git a/js&css/web-accessible/www.youtube.com/settings.js b/js&css/web-accessible/www.youtube.com/settings.js index 20bd387dd..407405adc 100644 --- a/js&css/web-accessible/www.youtube.com/settings.js +++ b/js&css/web-accessible/www.youtube.com/settings.js @@ -113,8 +113,7 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { if (option === 'header_left') { if (this.storage.header_position === 'normal' && this.elements.masthead.start) { this.elements.masthead.start.appendChild(button); - } - else if (this.elements.app_drawer.start) { + } else if (this.elements.app_drawer.start) { this.elements.app_drawer.start.appendChild(button); } } else if (option === 'header_right') { @@ -160,7 +159,9 @@ ImprovedTube.deleteYoutubeCookies = function () { document.cookie = name + '=; domain=.youtube.com; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT'; } - setTimeout(function () {location.reload();}, 100); + setTimeout(function () { + location.reload(); + }, 100); }; /*----------------------------------------------------------------------------- diff --git a/js&css/web-accessible/www.youtube.com/shortcuts.js b/js&css/web-accessible/www.youtube.com/shortcuts.js index c743907cc..645e4d4a0 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -421,15 +421,33 @@ ImprovedTube.shortcutActivateCaptions = function () { }; /*------Chapters------*/ ImprovedTube.shortcutChapters = function () { - try {var height = document.querySelector('*[target-id*=chapters]').clientHeight;} catch {} - if (height) {try {document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close")} catch {}} - else { try {document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open")} catch {} } + try { + var height = document.querySelector('*[target-id*=chapters]').clientHeight; + } catch {} + if (height) { + try { + document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close") + } catch {} + } else { + try { + document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open") + } catch {} + } }; /*------Transcript------*/ ImprovedTube.shortcutTranscript = function () { - try {var height = document.querySelector('*[target-id*=transcript]').clientHeight;} catch {} - if (height) {try {document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close")} catch {}} - else { try {document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open")} catch {} } + try { + var height = document.querySelector('*[target-id*=transcript]').clientHeight; + } catch {} + if (height) { + try { + document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close") + } catch {} + } else { + try { + document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open") + } catch {} + } }; /*------------------------------------------------------------------------------ 4.7.22 LIKE @@ -445,19 +463,47 @@ ImprovedTube.shortcutDislike = function () { }; /*------Report------*/ ImprovedTube.shortcutReport = function () { - try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); - document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} - catch {console.log("'...' failed"); setTimeout(function () {try {document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} - catch {console.log("'...' failed2")}}, 100) } - - setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} - catch {console.log("report failed"); setTimeout(function () {try {document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} - catch {console.log("report failed2"); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}}, 800); + try { + document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); + document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0) + } catch { + console.log("'...' failed"); setTimeout(function () { + try { + document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0) + } catch { + console.log("'...' failed2") + } + }, 100) } + + setTimeout(function () { + try { + document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click(); + } catch { + console.log("report failed"); setTimeout(function () { + try { + document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click(); + } catch { + console.log("report failed2"); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); + } + }, 800); + } }, 200); - setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed"); - setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed2");}}, 1700)}}, 700) + setTimeout(function () { + try { + document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1) + } catch { + console.log("dropdown visible failed"); + setTimeout(function () { + try { + document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1) + } catch { + console.log("dropdown visible failed2"); + } + }, 1700) + } + }, 700) } /*------------------------------------------------------------------------------ 4.7.24 SUBSCRIBE diff --git a/menu/index.js b/menu/index.js index 00617bcfb..b7630ac7e 100644 --- a/menu/index.js +++ b/menu/index.js @@ -7,7 +7,9 @@ --------------------------------------------------------------*/ satus.storage.import(function (items) { var language = items.language; - if (!language || language === 'default') { language = false;} + if (!language || language === 'default') { + language = false; + } satus.locale.import(language, function () { satus.render(extension.skeleton); diff --git a/menu/satus.js b/menu/satus.js index f885bbe9a..4bb833982 100644 --- a/menu/satus.js +++ b/menu/satus.js @@ -239,17 +239,33 @@ satus.isset = function (target, is_object) { /*------------------------------------------------------------- # is___(target) --------------------------------------------------------------*/ -satus.isFunction =function (target) {return typeof target ==='function';}; +satus.isFunction =function (target) { + return typeof target ==='function'; +}; satus.isArray = Array.isArray; -satus.isString = function (t) { return typeof t ==='string'; }; -satus.isNumber = function (t) { return (typeof t ==='number' && !isNaN(t)); }; -satus.isObject = function (t) { return (t instanceof Object && t !== null); }; -satus.isElement = function (t) { return (t instanceof Element || t instanceof HTMLDocument); }; -satus.isNodeList = function (t) { return t instanceof NodeList; }; -satus.isBoolean = function (t) { return (t === false || t === true); }; +satus.isString = function (t) { + return typeof t ==='string'; +}; +satus.isNumber = function (t) { + return (typeof t ==='number' && !isNaN(t)); +}; +satus.isObject = function (t) { + return (t instanceof Object && t !== null); +}; +satus.isElement = function (t) { + return (t instanceof Element || t instanceof HTMLDocument); +}; +satus.isNodeList = function (t) { + return t instanceof NodeList; +}; +satus.isBoolean = function (t) { + return (t === false || t === true); +}; /*---LOG------------------------------------------------------*/ -satus.log =function () {console.log.apply(null, arguments);}; +satus.log =function () { + console.log.apply(null, arguments); +}; /*-------------------------------------------------------------- @@ -911,7 +927,9 @@ satus.storage.import = function (keys, callback) { } // satus.log('STORAGE: data was successfully imported'); satus.events.trigger('storage-import'); - if (callback) { callback(items); } + if (callback) { + callback(items); + } loading.style.display = 'none'; }); }; @@ -1054,27 +1072,29 @@ satus.locale.import = function (code, callback, path) { importLocale(language, () => importLocale('en', callback)); } } else { // try chrome://settings/languages: - try {chrome.i18n.getAcceptLanguages(function (languages) { - languages = languages.map(language => language.replace('-', '_')); - for (let i = languages.length - 1; i >= 0; i--) { - if (languages[i].includes('_')) { - let languageWithoutCountryCode = languages[i].substring(0, 2); - - if (!languages.includes(languageWithoutCountryCode)) { - languages.splice(i + 1, 0, languageWithoutCountryCode); + try { + chrome.i18n.getAcceptLanguages(function (languages) { + languages = languages.map(language => language.replace('-', '_')); + for (let i = languages.length - 1; i >= 0; i--) { + if (languages[i].includes('_')) { + let languageWithoutCountryCode = languages[i].substring(0, 2); + + if (!languages.includes(languageWithoutCountryCode)) { + languages.splice(i + 1, 0, languageWithoutCountryCode); + } } } - } - languages.includes("en") || languages.push("en"); + languages.includes("en") || languages.push("en"); - languages.forEach((language, index) => index === languages.length - 1 ? importLocale(language, callback) : importLocale(language, () => {})); + languages.forEach((language, index) => index === languages.length - 1 ? importLocale(language, callback) : importLocale(language, () => {})); /* equals: languages.length === 1 && importLocale(languages[0], callback); languages.length === 2 && importLocale(languages[0], () => importLocale(languages[1], callback)); languages.length === 3 && importLocale(languages[0], () => importLocale(languages[1], () => importLocale(languages[2], callback))); ... */ // console.log(languages); - });} catch (error) { + }); + } catch (error) { // Finally, if code nor chrome://settings/languages are available, use window.navigator.language: let language = window.navigator.language.replace('-', '_'); diff --git a/menu/skeleton-parts/appearance.js b/menu/skeleton-parts/appearance.js index 9711cbef8..b3da19d60 100644 --- a/menu/skeleton-parts/appearance.js +++ b/menu/skeleton-parts/appearance.js @@ -838,10 +838,11 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { click: function () { setTimeout(() => { if (satus.storage.get('related_videos')==="Titles" - && satus.storage.get("relatedVideosPrev") ==="Titles") {if (!satus.storage.get('thumbnails_right')) { - this.nextSibling.nextSibling.click(); - satus.storage.set('relatedVideosPrev', "notTitles") - } + && satus.storage.get("relatedVideosPrev") ==="Titles") { + if (!satus.storage.get('thumbnails_right')) { + this.nextSibling.nextSibling.click(); + satus.storage.set('relatedVideosPrev', "notTitles") + } } }, 650) @@ -866,13 +867,15 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { value: false, id: 'transcript', on: { - click: function () { setTimeout(() => { - if (satus.storage.get('transcript')) { - if (satus.storage.get('no_page_margin')) { - this.nextSibling.nextSibling.click(); + click: function () { + setTimeout(() => { + if (satus.storage.get('transcript')) { + if (satus.storage.get('no_page_margin')) { + this.nextSibling.nextSibling.click(); + } } - } - }, 250); } + }, 250); + } } }, compact_spacing: { @@ -886,13 +889,15 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { value: false, on: { - click: function () { setTimeout(() => { - if (satus.storage.get('no_page_margin')) { - if (satus.storage.get('transcript')) { - this.previousSibling.previousSibling.click(); + click: function () { + setTimeout(() => { + if (satus.storage.get('no_page_margin')) { + if (satus.storage.get('transcript')) { + this.previousSibling.previousSibling.click(); + } } - } - }, 250); } + }, 250); + } } }, chapters: { diff --git a/menu/skeleton-parts/general.js b/menu/skeleton-parts/general.js index 4fdf67374..a12841953 100644 --- a/menu/skeleton-parts/general.js +++ b/menu/skeleton-parts/general.js @@ -229,13 +229,15 @@ extension.skeleton.main.layers.section.general = { component: 'switch', text: 'markWatchedVideos', on: { - click: function () { setTimeout(() => { - if (satus.storage.get('mark_watched_videos')) { - if (!satus.storage.get('track_watched_videos')) { - this.nextSibling.click(); + click: function () { + setTimeout(() => { + if (satus.storage.get('mark_watched_videos')) { + if (!satus.storage.get('track_watched_videos')) { + this.nextSibling.click(); + } } - } - }, 250); } + }, 250); + } } }, track_watched_videos: {