From 1f0e708a75566728c3f446d9849462311fa467fc Mon Sep 17 00:00:00 2001 From: 4yman <170770027+4yman-0@users.noreply.github.com> Date: Sun, 3 Nov 2024 08:44:21 +0100 Subject: [PATCH] Use vscode format (can make code ugly) --- background.js | 8 +- js&css/extension/core.js | 8 +- js&css/extension/functions.js | 2 +- js&css/extension/init.js | 24 +- .../www.youtube.com/general/general.js | 6 +- js&css/web-accessible/core.js | 54 +-- js&css/web-accessible/functions.js | 178 +++++----- js&css/web-accessible/init.js | 52 +-- .../www.youtube.com/appearance.js | 190 ++++++----- .../www.youtube.com/blocklist.js | 30 +- .../web-accessible/www.youtube.com/channel.js | 21 +- .../web-accessible/www.youtube.com/player.js | 314 ++++++++++-------- .../www.youtube.com/playlist.js | 59 ++-- .../www.youtube.com/settings.js | 16 +- .../www.youtube.com/shortcuts.js | 69 ++-- .../web-accessible/www.youtube.com/themes.js | 98 +++--- menu/functions.js | 2 +- menu/index.js | 2 +- 18 files changed, 601 insertions(+), 532 deletions(-) diff --git a/background.js b/background.js index 3d90595c5..2d92d4c26 100644 --- a/background.js +++ b/background.js @@ -18,7 +18,7 @@ /* Sidepanel Option chrome.storage.local.get('improvedTubeSidePanel', function (result) { - if ( result.improvedTubeSidePanel && result.improvedTubeSidePanel ) { + if (result.improvedTubeSidePanel) { chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }) } else {chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false }) } }); @@ -28,8 +28,8 @@ -----------------------------*/ chrome.runtime.onInstalled.addListener(function (installed) { if (installed.reason == 'update') { - // var thisVersion = chrome.runtime.getManifest().version; - // console.log("Updated from " + installed.previousVersion + " to " + thisVersion + "!"); + //var thisVersion = chrome.runtime.getManifest().version; + //console.log("Updated from " + installed.previousVersion + " to " + thisVersion + "!"); chrome.storage.local.get('description', function (result) { if (result.description === 'classic_expanded') { chrome.storage.local.set({description: 'expanded'}); @@ -37,7 +37,7 @@ chrome.runtime.onInstalled.addListener(function (installed) { }); // Shortcut renames: chrome.storage.local.get(['shortcut_auto', 'shortcut_144p', 'shortcut_240p', 'shortcut_360p', 'shortcut_480p', 'shortcut_720p', 'shortcut_1080p', 'shortcut_1440p', 'shortcut_2160p', 'shortcut_2880p', 'shortcut_4320p'], function (result) { - // validate and move to new name + // Validate and move to new name for (let [name, keys] of Object.entries(result)) { if (!keys) continue; let newKeys = {}, diff --git a/js&css/extension/core.js b/js&css/extension/core.js index bbb803d72..666826ffb 100644 --- a/js&css/extension/core.js +++ b/js&css/extension/core.js @@ -73,7 +73,7 @@ extension.events.on = function (type, listener, options = {}) { listeners[type] = []; } - if (options.async ) { + if (options.async) { listener = (function (original) { return async function () { return new Promise(original); @@ -81,7 +81,7 @@ extension.events.on = function (type, listener, options = {}) { })(listener); } - if (options.prepend ) { + if (options.prepend) { listeners[type].unshift(listener); } else { listeners[type].push(listener); @@ -100,7 +100,7 @@ extension.events.trigger = async function (type, data) { var listener = listeners[i]; if (typeof listener === 'function') { - if (listener instanceof(async function () {}).constructor ) { + if (listener instanceof (async function () { }).constructor) { await listener(data); } else { listener(data); @@ -298,7 +298,7 @@ extension.storage.load = function (callback) { // initialize theme in case YT is in Dark cookie mode if (!extension.storage.data['theme'] && document.documentElement.hasAttribute('dark')) { extension.storage.data['theme'] = 'dark'; - chrome.storage.local.set({theme: 'dark'}); + chrome.storage.local.set({ theme: 'dark' }); } for (const key in items) { diff --git a/js&css/extension/functions.js b/js&css/extension/functions.js index 4b6c9f742..479d0c3c2 100644 --- a/js&css/extension/functions.js +++ b/js&css/extension/functions.js @@ -5,5 +5,5 @@ --------------------------------------------------------------*/ extension.functions.getUrlParameter = function (url, parameter) { var match = url.match(new RegExp('(\\?|\\&)' + parameter + '=[^&]+')); - if (match) {return match[0].substr(3);} + 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 562f0b5ea..c545fa498 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(); @@ -141,11 +141,11 @@ document.addEventListener('it-message-from-youtube', function () { //console.log(message); - if (message.requestOptionsUrl ) { + if (message.requestOptionsUrl) { extension.messages.send({ responseOptionsUrl: chrome.runtime.getURL('menu/index.html') }); - } else if (message.onlyOnePlayer ) { + } else if (message.onlyOnePlayer) { chrome.runtime.sendMessage({ name: 'only-one-player' }); @@ -153,11 +153,11 @@ document.addEventListener('it-message-from-youtube', function () { chrome.runtime.sendMessage({ action: 'fixPopup', width: message.width, - height: message.height, + height: message.height, title: message.title, }); } else if (message.action === 'analyzer') { - if (extension.storage.data.analyzer_activation ) { + if (extension.storage.data.analyzer_activation) { var data = message.name, date = new Date().toDateString(), hours = new Date().getHours() + ':00'; @@ -186,7 +186,7 @@ document.addEventListener('it-message-from-youtube', function () { } } else if (message.action === 'blocklist') { if (!extension.storage.data.blocklist || typeof extension.storage.data.blocklist !== 'object') { - extension.storage.data.blocklist = {videos: {}, channels: {}}; + extension.storage.data.blocklist = { videos: {}, channels: {} }; } switch (message.type) { @@ -243,7 +243,7 @@ document.addEventListener('it-message-from-youtube', function () { }); } else if (message.action === 'set') { if (message.value) { - chrome.storage.local.set({[message.key]: message.value}); + chrome.storage.local.set({ [message.key]: message.value }); } else { chrome.storage.local.remove([message.key]); } @@ -252,17 +252,17 @@ document.addEventListener('it-message-from-youtube', function () { }); document.addEventListener('it-play', function () { - // var videos = document.querySelectorAll('video'); + // var videos = document.querySelectorAll('video'); try { - chrome.runtime.sendMessage({action: 'play'}) + chrome.runtime.sendMessage({ action: 'play' }) } catch (error) { console.log(error); setTimeout(function () { try { - chrome.runtime.sendMessage({action: 'play'}, function (response) { + chrome.runtime.sendMessage({ action: 'play' }, function (response) { console.log(response) - } ); - } catch {} + }); + } catch { } }, 321); } }); \ No newline at end of file diff --git a/js&css/extension/www.youtube.com/general/general.js b/js&css/extension/www.youtube.com/general/general.js index 1a9ee15ca..410926116 100644 --- a/js&css/extension/www.youtube.com/general/general.js +++ b/js&css/extension/www.youtube.com/general/general.js @@ -256,9 +256,9 @@ extension.features.popupWindowButtons = function (event) { if (!ytPlayer) { let shorts = /short/.test(this.parentElement.href); let vertical = false; - if ( width / height < 1 ) { vertical = true } - if ( !vertical && shorts ) { width = height * 0.6} - if ( vertical && !shorts ) { height = width * 0.6} + if (width / height < 1) { vertical = true } + 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}`); diff --git a/js&css/web-accessible/core.js b/js&css/web-accessible/core.js index ec6ee7ba3..c736c451e 100644 --- a/js&css/web-accessible/core.js +++ b/js&css/web-accessible/core.js @@ -100,7 +100,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/ @@ -184,9 +184,10 @@ document.addEventListener('it-message-from-extension', function () { ImprovedTube.storage = message.storage; 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'}, + 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; } @@ -204,20 +205,21 @@ document.addEventListener('it-message-from-extension', function () { ImprovedTube.init(); ImprovedTube.blocklistInit(); - // REACTION OR VISUAL FEEDBACK WHEN THE USER CHANGES A SETTING (already automated for our CSS features): + // REACTION OR VISUAL FEEDBACK WHEN THE USER CHANGES A SETTING (already automated for our CSS features): } else if (message.action === 'storage-changed') { let camelized_key = message.camelizedKey; ImprovedTube.storage[message.key] = message.value; if (['block_vp9', 'block_h264', 'block_av1'].includes(message.key)) { - let atlas = {block_vp9:'vp9|vp09', block_h264:'avc1', block_av1:'av01'} + 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'); } } - if (message.key==="player_60fps") { + if (message.key === "player_60fps") { if (ImprovedTube.storage.player_60fps === false) { localStorage['it-player30fps'] = true; } else { @@ -234,7 +236,7 @@ document.addEventListener('it-message-from-extension', function () { case 'playerPlaybackSpeed': case 'playerForcedPlaybackSpeed': if (ImprovedTube.storage.player_forced_playback_speed && isFinite(Number(ImprovedTube.storage.player_playback_speed))) { - ImprovedTube.playbackSpeed (Number(ImprovedTube.storage.player_playback_speed)); //new + ImprovedTube.playbackSpeed(Number(ImprovedTube.storage.player_playback_speed)); //new ImprovedTube.elements.player.setPlaybackRate(Number(ImprovedTube.storage.player_playback_speed)); // ImprovedTube.elements.player.querySelector('video').playbackRate = Number(ImprovedTube.storage.player_playback_speed.toFixed(2)); } else if (ImprovedTube.storage.player_forced_playback_speed === false) { @@ -252,14 +254,14 @@ document.addEventListener('it-message-from-extension', function () { case 'description': if (ImprovedTube.storage.description === "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") { - try {document.querySelector("#less").click() || document.querySelector("#collapse").click();} catch {} + try { document.querySelector("#less").click() || document.querySelector("#collapse").click(); } catch { } } break case 'transcript': - if (ImprovedTube.storage.transcript ) { + if (ImprovedTube.storage.transcript) { document.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility'); } else if (!ImprovedTube.storage.transcript) { document.querySelector('*[target-id*=transcript] #visibility-button button')?.click(); @@ -267,7 +269,7 @@ document.addEventListener('it-message-from-extension', function () { break case 'chapters': - if (ImprovedTube.storage.chapters ) { + if (ImprovedTube.storage.chapters) { document.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility'); } else if (!ImprovedTube.storage.chapters) { document.querySelector('*[target-id*=chapters] #visibility-button button')?.click(); @@ -286,9 +288,9 @@ document.addEventListener('it-message-from-extension', function () { case 'forcedTheaterMode': if (ImprovedTube.storage.forced_theater_mode === false && ImprovedTube.elements.ytd_watch && ImprovedTube.elements.player) { const button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); - if (button && ImprovedTube.elements.ytd_watch.theater ) { + if (button && ImprovedTube.elements.ytd_watch.theater) { ImprovedTube.elements.ytd_watch.theater = false; - setTimeout(function () { button.click();}, 100); + setTimeout(function () { button.click(); }, 100); } } break @@ -345,7 +347,7 @@ document.addEventListener('it-message-from-extension', function () { 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 ) { + } else if (ImprovedTube.storage.below_player_pip) { document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); } @@ -354,7 +356,7 @@ document.addEventListener('it-message-from-extension', function () { 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 ) { + } else if (ImprovedTube.storage.below_player_screenshot) { document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); } @@ -363,7 +365,7 @@ document.addEventListener('it-message-from-extension', function () { 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 ) { + } else if (ImprovedTube.storage.below_player_loop) { document.querySelectorAll('.improvedtube-player-button').forEach(e => e.remove()); ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer(); } @@ -372,7 +374,7 @@ document.addEventListener('it-message-from-extension', function () { case 'dayOfWeek': if (ImprovedTube.storage.day_of_week === false) { document.querySelector(".ytd-day-of-week")?.remove(); - } else if (ImprovedTube.storage.day_of_week ) { + } else if (ImprovedTube.storage.day_of_week) { ImprovedTube.dayOfWeek(); } break @@ -380,7 +382,7 @@ document.addEventListener('it-message-from-extension', function () { case 'playerRemainingDuration': if (ImprovedTube.storage.player_remaining_duration === false) { document.querySelector(".ytp-time-remaining-duration")?.remove(); - } else if (ImprovedTube.storage.player_remaining_duration ) { + } else if (ImprovedTube.storage.player_remaining_duration) { ImprovedTube.playerRemainingDuration(); } break @@ -401,8 +403,8 @@ document.addEventListener('it-message-from-extension', function () { ImprovedTube.playerControls(); break case 'playerlistUpNextAutoplay': - if (this.storage.playlist_up_next_autoplay ) { - if (playlistData.currentIndex != playlistData.localCurrentIndex) { playlistData.currentIndex = playlistData.localCurrentIndex;} + if (this.storage.playlist_up_next_autoplay) { + if (playlistData.currentIndex != playlistData.localCurrentIndex) { playlistData.currentIndex = playlistData.localCurrentIndex; } } break } @@ -411,19 +413,19 @@ 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 && ImprovedTube.elements.player) { + } else if (message.focus && ImprovedTube.elements.player) { ImprovedTube.focus = true; ImprovedTube.pageOnFocus(); - } else if (message.blur && ImprovedTube.elements.player) { + } else if (message.blur && ImprovedTube.elements.player) { ImprovedTube.focus = false; ImprovedTube.pageOnFocus(); document.dispatchEvent(new CustomEvent('improvedtube-blur')); - } else if (message.pause ) { + } else if (message.pause) { if (ImprovedTube.elements.player) { ImprovedTube.played_before_blur = ImprovedTube.elements.player.getPlayerState() === 1; ImprovedTube.elements.player.pauseVideo(); @@ -432,7 +434,7 @@ document.addEventListener('it-message-from-extension', function () { ImprovedTube.elements.player?.setVolume(message.setVolume); } else if (message.setPlaybackSpeed) { ImprovedTube.playbackSpeed(message.setPlaybackSpeed); - } else if (message.deleteCookies ) { + } else if (message.deleteCookies) { ImprovedTube.deleteYoutubeCookies(); } else if (message.responseOptionsUrl) { const iframe = document.querySelector('.it-button__iframe'); diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index aed329d37..84b51202b 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -54,16 +54,19 @@ ImprovedTube.ytElementsHandler = function (node) { var index = Array.prototype.indexOf.call(node.parentNode.children, node); if (index === 0) { - if (this.storage.playlist_reverse ) { + if (this.storage.playlist_reverse) { //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 { } } + } + } + } } this.playlistReverse(); } else if (index === 1) { @@ -71,16 +74,19 @@ ImprovedTube.ytElementsHandler = function (node) { this.playlistShuffle(); - if (this.storage.playlist_reverse ) { + if (this.storage.playlist_reverse) { //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 { } } + } + } + } } this.playlistReverse(); } @@ -105,15 +111,15 @@ ImprovedTube.ytElementsHandler = function (node) { this.howLongAgoTheVideoWasUploaded(); this.channelVideosCount(); } - //} else if (name === 'YTD-MENU-RENDERER' && node.classList.contains('ytd-video-primary-info-renderer')) { - // if (document.documentElement.dataset.pageType === 'video') { - // this.hideDetailButton(node.querySelector('#flexible-item-buttons').children); - // } + //} else if (name === 'YTD-MENU-RENDERER' && node.classList.contains('ytd-video-primary-info-renderer')) { + // if (document.documentElement.dataset.pageType === 'video') { + // this.hideDetailButton(node.querySelector('#flexible-item-buttons').children); + // } } else if (name === 'YTD-PLAYLIST-HEADER-RENDERER' || (name === 'YTD-MENU-RENDERER' && node.classList.contains('ytd-playlist-panel-renderer'))) { this.playlistPopup(); } else if (name === 'YTD-SUBSCRIBE-BUTTON-RENDERER' - || name === 'YT-SUBSCRIBE-BUTTON-VIEW-MODEL' - || (name === 'YTD-BUTTON-RENDERER' && node.classList.contains('ytd-c4-tabbed-header-renderer'))) { + || name === 'YT-SUBSCRIBE-BUTTON-VIEW-MODEL' + || (name === 'YTD-BUTTON-RENDERER' && node.classList.contains('ytd-c4-tabbed-header-renderer'))) { ImprovedTube.blocklistChannel(node); ImprovedTube.elements.subscribe_button = node; } else if (id === 'chat-messages') { @@ -122,7 +128,8 @@ ImprovedTube.ytElementsHandler = function (node) { this.livechat(); } else if (name === 'YTD-MASTHEAD') { if (!this.elements.masthead) { - this.elements.masthead = {start: node.querySelector('#start'), + this.elements.masthead = { + start: node.querySelector('#start'), end: node.querySelector('#end'), logo: node.querySelector('a#logo') }; @@ -131,9 +138,10 @@ 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'), + this.elements.app_drawer = { + start: node.querySelector('div#header'), logo: node.querySelector('a#logo') - }; + }; this.improvedtubeYoutubeIcon(); } @@ -170,9 +178,10 @@ ImprovedTube.ytElementsHandler = function (node) { ImprovedTube.playerAds(node); } } - }).observe(node, {childList: true, // attributes: true, - subtree: true - }); + }).observe(node, { + childList: true, // attributes: true, + subtree: true + }); } new MutationObserver(function (mutationList) { @@ -185,11 +194,12 @@ ImprovedTube.ytElementsHandler = function (node) { } } } - }).observe(ImprovedTube.elements.player_thumbnail, {attributes: true, + }).observe(ImprovedTube.elements.player_thumbnail, { + attributes: true, attributeFilter: ['style'], childList: false, subtree: false - }); + }); } } else if (name === 'YTD-WATCH-FLEXY') { this.elements.ytd_watch = node; @@ -201,40 +211,46 @@ ImprovedTube.ytElementsHandler = function (node) { node.calculateCurrentPlayerSize_ = function () { if (!this.theater && ImprovedTube.elements.player) { if (this.updateStyles) { - this.updateStyles({'--ytd-watch-flexy-width-ratio': 1, - '--ytd-watch-flexy-height-ratio': 0.5625 - }); - - this.updateStyles({'--ytd-watch-width-ratio': 1, - '--ytd-watch-height-ratio': 0.5625 - }); + this.updateStyles({ + '--ytd-watch-flexy-width-ratio': 1, + '--ytd-watch-flexy-height-ratio': 0.5625 + }); + + this.updateStyles({ + '--ytd-watch-width-ratio': 1, + '--ytd-watch-height-ratio': 0.5625 + }); } - return {width: ImprovedTube.elements.player.offsetWidth, + return { + width: ImprovedTube.elements.player.offsetWidth, height: Math.round(ImprovedTube.elements.player.offsetWidth / (16 / 9)) - }; + }; } - return {width: NaN, // ?? + return { + width: NaN, // ?? height: NaN - }; + }; }; node.calculateNormalPlayerSize_ = node.calculateCurrentPlayerSize_; // ?? } } 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); - // } else if (id === 'below') { setTimeout(function () {}, 0); - } else if (id === 'panels') { setTimeout(function () { ImprovedTube.transcript(node); ImprovedTube.chapters(node);ImprovedTube.elements.panels = node;}, 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') { + setTimeout(function () { ImprovedTube.transcript(node); ImprovedTube.chapters(node); ImprovedTube.elements.panels = node; }, 200); } /* else if (name === 'TP-YT-PAPER-BUTTON') { if ( (id === 'expand-sizer' || id === 'expand') && node.parentNode.id === 'description-inline-expander') { setTimeout(function () { ImprovedTube.expandDescription(node); console.log("EXPAND DESCRIPTION, OLD WAY") }, 750); }} */ - } else if (id === 'panels') { + } else if (id === 'panels') { ImprovedTube.elements.panels = node; } }; @@ -264,7 +280,8 @@ ImprovedTube.videoPageUpdate = function () { var video_id = this.getParam(new URL(location.href).search.substr(1), 'v'); if (this.storage.track_watched_videos && video_id) { - ImprovedTube.messages.send({action: 'watched', + ImprovedTube.messages.send({ + action: 'watched', type: 'add', id: video_id, title: document.title @@ -279,7 +296,7 @@ ImprovedTube.videoPageUpdate = function () { ImprovedTube.upNextAutoplay(); ImprovedTube.playerAutofullscreen(); ImprovedTube.playerSize(); - if (this.storage.player_always_repeat ) { ImprovedTube.playerRepeat(); }; + if (this.storage.player_always_repeat) { ImprovedTube.playerRepeat(); }; ImprovedTube.playerScreenshotButton(); ImprovedTube.playerRepeatButton(); ImprovedTube.playerRotateButton(); @@ -336,7 +353,7 @@ ImprovedTube.initPlayer = function () { ImprovedTube.playerQuality(); ImprovedTube.batteryFeatures(); ImprovedTube.playerVolume(); - if (this.storage.player_always_repeat ) { ImprovedTube.playerRepeat(); } + if (this.storage.player_always_repeat) { ImprovedTube.playerRepeat(); } ImprovedTube.playerScreenshotButton(); ImprovedTube.playerRepeatButton(); ImprovedTube.playerRotateButton(); @@ -345,7 +362,7 @@ ImprovedTube.initPlayer = function () { ImprovedTube.playerHamburgerButton(); ImprovedTube.playerControls(); ImprovedTube.expandDescription(); - setTimeout(function () {ImprovedTube.forcedTheaterMode(); }, 150); + setTimeout(function () { ImprovedTube.forcedTheaterMode(); }, 150); if (location.href.indexOf('/embed/') === -1) { ImprovedTube.miniPlayer(); } } }; @@ -372,34 +389,37 @@ ImprovedTube.playerOnTimeUpdate = function () { ImprovedTube.playerPlaybackSpeed(); } - if (ImprovedTube.storage.always_show_progress_bar ) {ImprovedTube.showProgressBar();} - if (ImprovedTube.storage.player_remaining_duration ) {ImprovedTube.playerRemainingDuration();} + if (ImprovedTube.storage.always_show_progress_bar) { ImprovedTube.showProgressBar(); } + if (ImprovedTube.storage.player_remaining_duration) { ImprovedTube.playerRemainingDuration(); } ImprovedTube.played_time += .5; }, 500); } clearInterval(noTimeUpdate); noTimeUpdate = setTimeout(function () { - clearInterval(timeUpdateInterval); + clearInterval(timeUpdateInterval); timeUpdateInterval = null; }, 987); }; ImprovedTube.playerOnLoadedMetadata = function () { - setTimeout(function () {ImprovedTube.playerSize();}, 100); - setTimeout(function () { if (ImprovedTube.elements.panels) { - ImprovedTube.transcript(ImprovedTube.elements.panels); - ImprovedTube.chapters(ImprovedTube.elements.panels); - }}, 250); + setTimeout(function () { ImprovedTube.playerSize(); }, 100); + setTimeout(function () { + if (ImprovedTube.elements.panels) { + ImprovedTube.transcript(ImprovedTube.elements.panels); + ImprovedTube.chapters(ImprovedTube.elements.panels); + } + }, 250); }; ImprovedTube.playerOnPause = function (event) { ImprovedTube.playlistUpNextAutoplay(event); if (ImprovedTube.elements.yt_channel_name) { - ImprovedTube.messages.send({action: 'analyzer', + ImprovedTube.messages.send({ + action: 'analyzer', name: ImprovedTube.elements.yt_channel_name.__data.tooltipText, time: ImprovedTube.played_time - }); + }); } ImprovedTube.played_time = 0; ImprovedTube.playerControls(); @@ -408,13 +428,13 @@ ImprovedTube.playerOnPause = function (event) { }; if (document.documentElement.dataset.pageType === 'video' - && (ImprovedTube.storage.description === "expanded" || ImprovedTube.storage.transcript || ImprovedTube.storage.chapters )) { - ImprovedTube.forbidFocus = function (ms) { + && (ImprovedTube.storage.description === "expanded" || ImprovedTube.storage.transcript || ImprovedTube.storage.chapters)) { + ImprovedTube.forbidFocus = function (ms) { const originalFocus = HTMLElement.prototype.focus; // Backing up default method - other methods: Element.prototype.scrollIntoView window.scrollTo window.scrollBy // Override YouTube's scroll method: - HTMLElement.prototype.focus = function() {console.log("Preventing YouTube's scripted scrolling, when expanding the video description for you"); } - if(document.hidden) ms = 3*ms; - setTimeout(function() { HTMLElement.prototype.focus = originalFocus; }, ms); // Restoring JS's "focus()" + HTMLElement.prototype.focus = function () { console.log("Preventing YouTube's scripted scrolling, when expanding the video description for you"); } + if (document.hidden) ms = 3 * ms; + setTimeout(function () { HTMLElement.prototype.focus = originalFocus; }, ms); // Restoring JS's "focus()" } } @@ -422,11 +442,12 @@ if (document.documentElement.dataset.pageType === 'video' ImprovedTube.playerOnEnded = function (event) { ImprovedTube.playlistUpNextAutoplay(event); - ImprovedTube.messages.send({action: 'analyzer', + ImprovedTube.messages.send({ + action: 'analyzer', //adding "?" (not a fix) name: ImprovedTube.elements.yt_channel_name?.__data.tooltipText, time: ImprovedTube.played_time - }); + }); ImprovedTube.played_time = 0; }; @@ -467,7 +488,7 @@ ImprovedTube.onmousedown = function () { 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)) + && (/html5-(main-video|video-container)|ytp-play-button/.test(path[i].className)) ) {ImprovedTube.user_interacted = true;} } } @@ -609,8 +630,9 @@ 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 () { + tooltip.style.zIndex = 10001; + } // needed for cinema mode + function mouseleave() { tooltip.remove(); this.removeEventListener('mouseleave', mouseleave); @@ -645,8 +667,8 @@ 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'); @@ -664,17 +686,17 @@ 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 ca6596ca6..d88fdfb94 100644 --- a/js&css/web-accessible/init.js +++ b/js&css/web-accessible/init.js @@ -57,7 +57,7 @@ ImprovedTube.observer = new MutationObserver(function (mutationList) { subtree: true }); -if (ImprovedTube.storage.channel_default_tab && ImprovedTube.storage.channel_default_tab !== '/' ) { +if (ImprovedTube.storage.channel_default_tab && ImprovedTube.storage.channel_default_tab !== '/') { new MutationObserver(function (mutationList) { for (var i = 0, l = mutationList.length; i < l; i++) { var mutation = mutationList[i]; @@ -106,30 +106,30 @@ ImprovedTube.init = function () { }; document.addEventListener('yt-navigate-finish', function () { -/* if (name === 'META') { // infos are not updated when clicking related videos... + /* if (name === 'META') { // infos are not updated when clicking related videos... if(node.getAttribute('name')) { - //if(node.getAttribute('name') === 'title') {ImprovedTube.title = node.content;} //duplicate - //if(node.getAttribute('name') === 'description') {ImprovedTube.description = node.content;} //duplicate - //if node.getAttribute('name') === 'themeColor') {ImprovedTube.themeColor = node.content;} //might help our darkmode/themes -//Do we need any of these here before the player starts? - //if(node.getAttribute('name') === 'keywords') {ImprovedTube.keywords = node.content;} - } else if (node.getAttribute('itemprop')) { - //if(node.getAttribute('itemprop') === 'name') {ImprovedTube.title = node.content;} - if(node.getAttribute('itemprop') === 'genre') {ImprovedTube.category = node.content;} - //if(node.getAttribute('itemprop') === 'channelId') {ImprovedTube.channelId = node.content;} - //if(node.getAttribute('itemprop') === 'videoId') {ImprovedTube.videoId = node.content;} -//The following infos will enable awesome, smart features. Some of which everyone should use. - //if(node.getAttribute('itemprop') === 'description') {ImprovedTube.description = node.content;} - //if(node.getAttribute('itemprop') === 'duration') {ImprovedTube.duration = node.content;} - //if(node.getAttribute('itemprop') === 'interactionCount'){ImprovedTube.views = node.content;} - //if(node.getAttribute('itemprop') === 'isFamilyFriendly'){ImprovedTube.isFamilyFriendly = node.content;} - //if(node.getAttribute('itemprop') === 'unlisted') {ImprovedTube.unlisted = node.content;} - //if(node.getAttribute('itemprop') === 'regionsAllowed'){ImprovedTube.regionsAllowed = node.content;} - //if(node.getAttribute('itemprop') === 'paid') {ImprovedTube.paid = node.content;} - // if(node.getAttribute('itemprop') === 'datePublished' ){ImprovedTube.datePublished = node.content;} - //to use in the "how long ago"-feature, not to fail without API key? just like the "day-of-week"-feature above - // if(node.getAttribute('itemprop') === 'uploadDate') {ImprovedTube.uploadDate = node.content;} -*/ + //if(node.getAttribute('name') === 'title') {ImprovedTube.title = node.content;} //duplicate + //if(node.getAttribute('name') === 'description') {ImprovedTube.description = node.content;} //duplicate + //if node.getAttribute('name') === 'themeColor') {ImprovedTube.themeColor = node.content;} //might help our darkmode/themes + //Do we need any of these here before the player starts? + //if(node.getAttribute('name') === 'keywords') {ImprovedTube.keywords = node.content;} + } else if (node.getAttribute('itemprop')) { + //if(node.getAttribute('itemprop') === 'name') {ImprovedTube.title = node.content;} + if(node.getAttribute('itemprop') === 'genre') {ImprovedTube.category = node.content;} + //if(node.getAttribute('itemprop') === 'channelId') {ImprovedTube.channelId = node.content;} + //if(node.getAttribute('itemprop') === 'videoId') {ImprovedTube.videoId = node.content;} + //The following infos will enable awesome, smart features. Some of which everyone should use. + //if(node.getAttribute('itemprop') === 'description') {ImprovedTube.description = node.content;} + //if(node.getAttribute('itemprop') === 'duration') {ImprovedTube.duration = node.content;} + //if(node.getAttribute('itemprop') === 'interactionCount'){ImprovedTube.views = node.content;} + //if(node.getAttribute('itemprop') === 'isFamilyFriendly'){ImprovedTube.isFamilyFriendly = node.content;} + //if(node.getAttribute('itemprop') === 'unlisted') {ImprovedTube.unlisted = node.content;} + //if(node.getAttribute('itemprop') === 'regionsAllowed'){ImprovedTube.regionsAllowed = node.content;} + //if(node.getAttribute('itemprop') === 'paid') {ImprovedTube.paid = node.content;} + // if(node.getAttribute('itemprop') === 'datePublished' ){ImprovedTube.datePublished = node.content;} + //to use in the "how long ago"-feature, not to fail without API key? just like the "day-of-week"-feature above + // if(node.getAttribute('itemprop') === 'uploadDate') {ImprovedTube.uploadDate = node.content;} + */ ImprovedTube.pageType(); ImprovedTube.YouTubeExperiments(); ImprovedTube.commentsSidebar(); @@ -139,7 +139,7 @@ document.addEventListener('yt-navigate-finish', function () { ImprovedTube.initPlayer(); } - if (document.documentElement.dataset.pageType === 'home' && ImprovedTube.storage.youtube_home_page === 'search' ) { + if (document.documentElement.dataset.pageType === 'home' && ImprovedTube.storage.youtube_home_page === 'search') { document.querySelector('body').style.setProperty('visibility', 'visible', 'important'); ImprovedTube.shortcutGoToSearchBox(); document.querySelector('#search').click(); @@ -161,7 +161,7 @@ window.addEventListener('load', function () { } ImprovedTube.improvedtubeYoutubeIcon(); if (document.documentElement.dataset.pageType === 'video') { ImprovedTube.expandDescription(); } - if (document.documentElement.dataset.pageType === 'home' && ImprovedTube.storage.youtube_home_page === 'search' ) { + if (document.documentElement.dataset.pageType === 'home' && ImprovedTube.storage.youtube_home_page === 'search') { document.querySelector('body').style.setProperty('visibility', 'visible', 'important'); ImprovedTube.shortcutGoToSearchBox(); document.querySelector('#search').click(); diff --git a/js&css/web-accessible/www.youtube.com/appearance.js b/js&css/web-accessible/www.youtube.com/appearance.js index 81f70eb21..653d2ed10 100644 --- a/js&css/web-accessible/www.youtube.com/appearance.js +++ b/js&css/web-accessible/www.youtube.com/appearance.js @@ -2,30 +2,31 @@ APPEARANCE ------------------------------------------------------------------------------*/ ImprovedTube.YouTubeExperiments = function () { - if ((this.storage.undo_the_new_sidebar === "true" || this.storage.description === "sidebar") + if ((this.storage.undo_the_new_sidebar === "true" || this.storage.description === "sidebar") && document.documentElement.dataset.pageType === 'video') { - if (window.yt?.config_?.EXPERIMENT_FLAGS) { - const newSidebarFlags = [ - 'kevlar_watch_grid', - 'small_avatars_for_comments', - 'small_avatars_for_comments_ep', - 'web_watch_rounded_player_large' - ]; - if (this.storage.undo_the_new_sidebar === "true") { - if (window.yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid ) { - try { - newSidebarFlags.forEach(F => { - Object.defineProperty(window.yt.config_.EXPERIMENT_FLAGS, F, { get: () => false }); - }); - } catch (error) { console.error("can't undo description on the side", error); } - }} else if (this.storage.description === "sidebar" && window.yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid !== true) { - try { - newSidebarFlags.forEach(F => { - Object.defineProperty(window.yt.config_.EXPERIMENT_FLAGS, F, { get: () => true }); - }); - } catch (error) { console.error("tried to move description to the sidebar", error); } - } - } else { console.log ("yt.config_.EXPERIMENT_FLAGS is not yet defined") } + if (window.yt?.config_?.EXPERIMENT_FLAGS) { + const newSidebarFlags = [ + 'kevlar_watch_grid', + 'small_avatars_for_comments', + 'small_avatars_for_comments_ep', + 'web_watch_rounded_player_large' + ]; + if (this.storage.undo_the_new_sidebar === "true") { + if (window.yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid) { + try { + newSidebarFlags.forEach(F => { + Object.defineProperty(window.yt.config_.EXPERIMENT_FLAGS, F, { get: () => false }); + }); + } catch (error) { console.error("can't undo description on the side", error); } + } + } else if (this.storage.description === "sidebar" && window.yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid !== true) { + try { + newSidebarFlags.forEach(F => { + Object.defineProperty(window.yt.config_.EXPERIMENT_FLAGS, F, { get: () => true }); + }); + } catch (error) { console.error("tried to move description to the sidebar", error); } + } + } else { console.log("yt.config_.EXPERIMENT_FLAGS is not yet defined") } } } /* try { @@ -66,7 +67,7 @@ ImprovedTube.playerSize = function () { FORCED THEATER MODE ------------------------------------------------------------------------------*/ ImprovedTube.forcedTheaterMode = function () { - if (ImprovedTube.storage.forced_theater_mode && ImprovedTube.elements.ytd_watch && ImprovedTube.elements.player) { + if (ImprovedTube.storage.forced_theater_mode && 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"; @@ -81,7 +82,7 @@ ImprovedTube.forcedTheaterMode = function () { HD THUMBNAIL ------------------------------------------------------------------------------*/ ImprovedTube.playerHdThumbnail = function () { - if (this.storage.player_hd_thumbnail ) { + if (this.storage.player_hd_thumbnail) { var thumbnail = ImprovedTube.elements.player_thumbnail; if (thumbnail.style.backgroundImage.indexOf("/hqdefault.jpg") !== -1) { @@ -141,7 +142,7 @@ ImprovedTube.showProgressBar = function () { ------------------------------------------------------------------------------*/ ImprovedTube.formatSecond = function (rTime) { var time = new Date(null); - if (this.storage.duration_with_speed ) { + if (this.storage.duration_with_speed) { var playbackRate = this.elements.video.playbackRate; time.setSeconds(rTime / playbackRate); } else { @@ -172,14 +173,15 @@ ImprovedTube.playerRemainingDuration = function () { Comments Sidebar Simple ------------------------------------------------------------------------------*/ ImprovedTube.commentsSidebarSimple = function () { - if (ImprovedTube.storage.comments_sidebar_simple ) { + if (ImprovedTube.storage.comments_sidebar_simple) { 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"));} + document.querySelector("#primary-inner").appendChild(document.querySelector("#related")); + } ); } } @@ -188,7 +190,7 @@ ImprovedTube.commentsSidebarSimple = function () { Comments Sidebar ------------------------------------------------------------------------------*/ ImprovedTube.commentsSidebar = function () { - if (!ImprovedTube.storage.comments_sidebar ) { + if (!ImprovedTube.storage.comments_sidebar) { return; } const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); @@ -201,14 +203,14 @@ ImprovedTube.commentsSidebar = function () { window.addEventListener("resize", sidebar) } - function sidebar () { + function sidebar() { resizePlayer(); if (window.matchMedia("(min-width: 1952px)").matches) { if (!hasApplied) { initialSetup() - setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) + 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 } @@ -235,7 +237,7 @@ ImprovedTube.commentsSidebar = function () { hasApplied = 0; } } - function setGrid () { + function setGrid() { let checkParentInterval = setInterval(() => { container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; if (container) { @@ -246,7 +248,7 @@ ImprovedTube.commentsSidebar = function () { } }, 250); } - function initialSetup () { + function initialSetup() { let secondaryInner = document.getElementById("secondary-inner"); let primaryInner = document.getElementById("primary-inner"); let comments = document.querySelector("#comments"); @@ -257,7 +259,7 @@ ImprovedTube.commentsSidebar = function () { secondaryInner.appendChild(comments); }) } - function resizePlayer () { + function resizePlayer() { const width = video.offsetWidth + 24; if (width != 24) { const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); @@ -265,14 +267,14 @@ ImprovedTube.commentsSidebar = function () { 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"]; - else [color, colorHover] = ["#aaaaaa", "#717171"]; + else[color, colorHover] = ["#aaaaaa", "#717171"]; const style = document.createElement("style"); - if (ImprovedTube.storage.comments_sidebar_scrollbars ) { + if (ImprovedTube.storage.comments_sidebar_scrollbars) { const cssRule = ` #primary, #secondary { overflow: overlay !important; @@ -296,7 +298,8 @@ ImprovedTube.commentsSidebar = function () { }`; style.appendChild(document.createTextNode(cssRule)); } - else { const cssRule = ` + else { + const cssRule = ` #primary, #secondary { overflow: overlay !important; } @@ -305,17 +308,17 @@ ImprovedTube.commentsSidebar = function () { width: 0px; height: 0px; }`; - style.appendChild(document.createTextNode(cssRule)); + style.appendChild(document.createTextNode(cssRule)); } 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); @@ -332,7 +335,7 @@ ImprovedTube.commentsSidebar = function () { TRANSCRIPT --------------------------------------------------------------*/ ImprovedTube.transcript = function (el) { - if (ImprovedTube.storage.transcript ) { + if (ImprovedTube.storage.transcript) { return; } const available = el.querySelector('[target-id*=transcript][visibility*=HIDDEN]') || el.querySelector('[target-id*=transcript]')?.clientHeight; @@ -340,14 +343,14 @@ ImprovedTube.transcript = function (el) { ImprovedTube.forbidFocus(2100); const descriptionTranscript = el.querySelector('ytd-video-description-transcript-section-renderer button[aria-label]'); descriptionTranscript ? descriptionTranscript.click() : el.querySelector('[target-id*=transcript]')?.removeAttribute('visibility'); - if ( yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid ) { available.setAttribute('z-index', '98765') } - } + if (yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid) { available.setAttribute('z-index', '98765') } + } }; /*---------------------------------------------------------------- CHAPTERS --------------------------------------------------------------*/ ImprovedTube.chapters = function (el) { - if (!ImprovedTube.storage.chapters ) { + if (!ImprovedTube.storage.chapters) { return; } const available = el.querySelector('[target-id*=chapters][visibility*=HIDDEN]') || el.querySelector('[target-id*=chapters]')?.clientHeight; @@ -355,9 +358,9 @@ ImprovedTube.chapters = function (el) { ImprovedTube.forbidFocus(2100); const modernChapters = el.querySelector('[modern-chapters] #navigation-button button[aria-label]'); modernChapters ? modernChapters.click() : el.querySelector('[target-id*=chapters]')?.removeAttribute('visibility'); - if ( yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid ) { available.setAttribute('z-index', '98765') } - } -}; + if (yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid) { available.setAttribute('z-index', '98765') } + } +}; /*------------------------------------------------------------------------------ LIVECHAT ------------------------------------------------------------------------------*/ @@ -382,20 +385,20 @@ 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'); - /* 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 (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 ) { + if (this.storage.below_player_loop) { 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 ) { transparentOrOn = 1; } + var transparentOrOn = .5; if (this.storage.player_always_repeat) { transparentOrOn = 1; } button.className = 'improvedtube-player-button'; button.id = 'it-below-player-loop'; button.dataset.tooltip = 'Loop'; @@ -407,13 +410,13 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { var video = ImprovedTube.elements.video, svg = this.children[0]; - function matchLoopState (opacity) { - svg.style.opacity = opacity; - if (ImprovedTube.storage.player_repeat_button ) { - var otherButton = document.querySelector('#it-repeat-button'); - otherButton.style.opacity = opacity; - } - } + function matchLoopState(opacity) { + svg.style.opacity = opacity; + if (ImprovedTube.storage.player_repeat_button) { + var otherButton = document.querySelector('#it-repeat-button'); + otherButton.style.opacity = opacity; + } + } if (video.hasAttribute('loop')) { video.removeAttribute('loop'); matchLoopState('.5') @@ -423,10 +426,10 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { } }; - svg.appendChild(path); button.appendChild(svg); + svg.appendChild(path); button.appendChild(svg); section.insertAdjacentElement('afterend', button) } - if (this.storage.below_player_pip ) { + if (this.storage.below_player_pip) { 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'); @@ -441,11 +444,11 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { ImprovedTube.enterPip(); }; - svg.appendChild(path); button.appendChild(svg); + svg.appendChild(path); button.appendChild(svg); section.insertAdjacentElement('afterend', button) } - if (this.storage.below_player_screenshot ) { + if (this.storage.below_player_screenshot) { 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'); @@ -458,10 +461,10 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { button.onclick = ImprovedTube.screenshot; - svg.appendChild(path); button.appendChild(svg); + svg.appendChild(path); button.appendChild(svg); section.insertAdjacentElement('afterend', button) } - } + } } }; /*------------------------------------------------------------------------------ @@ -469,22 +472,24 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { ------------------------------------------------------------------------------*/ ImprovedTube.expandDescription = function (el) { if (this.storage.description === "expanded") { - if (el) { + if (el) { ImprovedTube.forbidFocus(2100); // setTimeout(function () {ImprovedTube.elements.player.focus();}, 2500); el.click(); } else { // wait for the description - 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 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) { if (el) { ImprovedTube.forbidFocus(2600); // setTimeout(function () {ImprovedTube.elements.player.focus();}, 1000); - el.click(); + el.click(); clearInterval(waitForDescription); } el = document.querySelector('#description-inline-expander') - intervalMs *= 1.11; }}, intervalMs); - } + intervalMs *= 1.11; + } + }, intervalMs); + } } } /*------------------------------------------------------------------------------ @@ -505,12 +510,13 @@ ImprovedTube.expandDescription = function (el) { DAY OF WEEK --------------------------------------------------------------*/ ImprovedTube.dayOfWeek = function () { - if (this.storage.day_of_week ) { + if (this.storage.day_of_week) { var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; setTimeout(function () { //YouTube related video or internal link?: - var videoDate; try { videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate - } catch { try { videoDate = document.querySelector("[itemprop=datePublished]").content; } catch { } } - //..no? must be new session? + var videoDate; try { + videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate + } 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) { @@ -518,9 +524,11 @@ ImprovedTube.dayOfWeek = function () { 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); @@ -530,12 +538,12 @@ ImprovedTube.dayOfWeek = function () { HOW LONG AGO THE VIDEO WAS UPLOADED ------------------------------------------------------------------------------*/ ImprovedTube.howLongAgoTheVideoWasUploaded = function () { - if (this.storage.how_long_ago_the_video_was_uploaded && this.elements.yt_channel_name) { + if (this.storage.how_long_ago_the_video_was_uploaded && 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) { + function timeSince(date) { var seconds = Math.floor((new Date() - new Date(date)) / 1000), interval = Math.floor(seconds / 31536000); @@ -589,7 +597,7 @@ ImprovedTube.howLongAgoTheVideoWasUploaded = function () { SHOW CHANNEL VIDEOS COUNT ------------------------------------------------------------------------------*/ ImprovedTube.channelVideosCount = function () { - if (this.storage.channel_videos_count && this.elements.yt_channel_link) { + if (this.storage.channel_videos_count && 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(), @@ -635,10 +643,10 @@ ImprovedTube.channelVideosCount = function () { xhr.send(); } }; -if (ImprovedTube.storage.header_transparent2 ) { +if (ImprovedTube.storage.header_transparent2) { /*------------------------------------------------------------------------------ - TURN TOP BAR TRANSPARENT WHEN SCROLLING - ------------------------------------------------------------------------------*/ + 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'); @@ -650,7 +658,7 @@ if (ImprovedTube.storage.header_transparent2 ) { } }); - function handleScroll () { + function handleScroll() { var scrollTop = window.pageYOffset || document.documentElement.scrollTop; var buttonsContainer = document.getElementById('buttons'); @@ -662,11 +670,11 @@ if (ImprovedTube.storage.header_transparent2 ) { } /*------------------------------------------------------------------------------ - CHECK IF USER IS SCROLLING - ------------------------------------------------------------------------------*/ + CHECK IF USER IS SCROLLING + ------------------------------------------------------------------------------*/ window.addEventListener("scroll", handleScroll); - function getScrollDirection () { + function getScrollDirection() { var lastScrollTop = 0; return function () { var st = window.pageYOffset || document.documentElement.scrollTop; diff --git a/js&css/web-accessible/www.youtube.com/blocklist.js b/js&css/web-accessible/www.youtube.com/blocklist.js index 6c154b57e..c9feecd7c 100644 --- a/js&css/web-accessible/www.youtube.com/blocklist.js +++ b/js&css/web-accessible/www.youtube.com/blocklist.js @@ -150,7 +150,7 @@ ImprovedTube.blocklistChannel = function (node) { node.parentNode.parentNode.appendChild(button); } }); - this.blocklistChannelObserver.observe(node.parentNode.parentNode, {childList: true, subtree: true}); + this.blocklistChannelObserver.observe(node.parentNode.parentNode, { childList: true, subtree: true }); }; ImprovedTube.blocklistInit = function () { @@ -158,7 +158,7 @@ ImprovedTube.blocklistInit = function () { // initialize and (re)scan whole page. Called on load after 'storage-loaded' // and blocklist 'storage-changed' event (adding/removing blocks) if (!this.storage.blocklist || typeof this.storage.blocklist !== 'object') { - this.storage.blocklist = {videos: {}, channels: {}}; + this.storage.blocklist = { videos: {}, channels: {} }; } if (!this.storage.blocklist.videos || typeof this.storage.blocklist.channels !== 'object') { this.storage.blocklist.videos = {}; @@ -233,31 +233,31 @@ 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; + // list next to player + // node.parentNode.__dataHost.$.dismissible; case 'ytd-rich-item-renderer': - // short reel + // short reel case 'ytd-rich-grid-media': - // grid reel + // grid reel case 'ytd-rich-grid-slim-media': - // short grid reel + // short grid reel case 'ytd-playlist-video-renderer': - // playlist page + // playlist page case 'ytd-playlist-panel-video-renderer': - // playlist next to player - // node.parentNode.closest('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 + // 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 + // search results case 'ytd-video-preview': // subscriptions/search thumbnail video-preview return node.parentNode.parentNode.parentNode; case 'ytd-grid-video-renderer': - // channel home screen grid + // channel home screen grid case 'ytd-reel-item-renderer': // reel return node.parentNode.parentNode; diff --git a/js&css/web-accessible/www.youtube.com/channel.js b/js&css/web-accessible/www.youtube.com/channel.js index 04b641a3b..0f08d09a2 100644 --- a/js&css/web-accessible/www.youtube.com/channel.js +++ b/js&css/web-accessible/www.youtube.com/channel.js @@ -57,19 +57,20 @@ var compact = compact || {} ImprovedTube.channelCompactTheme = function () { compact.eventHandlerFns = compact.eventHandlerFns || [] compact.styles = compact.styles || [] - if (this.storage.channel_compact_theme ) { + if (this.storage.channel_compact_theme) { 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")} + 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 = {} } - function styleWithInterval () { + function styleWithInterval() { compact.listener = setInterval(() => { let item = document.querySelector(`#sections ytd-guide-section-renderer:nth-child(4) #items`) if (item) { @@ -79,7 +80,7 @@ ImprovedTube.channelCompactTheme = function () { }, 250) } - function styleWithListeners () { + function styleWithListeners() { compact.parents = [] compact.subs = [] for (let i = 0; i <= 2; i++) { @@ -90,7 +91,7 @@ ImprovedTube.channelCompactTheme = function () { let isCompact = localStorage.getItem(`ImprovedTube-compact-${i}`) === "true"; isCompact ? (sub.style.display = "none") : null; - function eventHandlerFn () { + function eventHandlerFn() { if (!isCompact) { sub.style.display = "none" isCompact = true @@ -107,7 +108,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] @@ -117,14 +118,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; @@ -135,7 +136,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 19cfa1f25..e9711f42c 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -7,7 +7,7 @@ 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 (there is a player) and (no user clicks) and (no ads playing) // and( ((auto play is off and it is not in a playlist) @@ -130,28 +130,26 @@ ImprovedTube.playbackSpeed = function (newSpeed) { PERMANENT PLAYBACK SPEED ------------------------------------------------------------------------------*/ ImprovedTube.playerPlaybackSpeed = function () { - if (!this.storage.player_forced_playback_speed ) { + if (!this.storage.player_forced_playback_speed) { return; } var player = this.elements.player; if (!player) return; - var video = this.elements.video || player.querySelector('video'); - option = this.storage.player_playback_speed; + var video = this.elements.video || player.querySelector('video'); + option = this.storage.player_playback_speed; if (this.isset(option) === false) { option = 1; } - else if ( option !== 1 ) { + else if (option !== 1) { const speed = video?.playbackRate ? Number(video.playbackRate.toFixed(2)) : (player?.getPlaybackRate ? Number(player.getPlaybackRate().toFixed(2)) : null); - if ( speed !== option && (speed > 1 || speed < 1) ) - { console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; } + if (speed !== option && (speed > 1 || speed < 1)) { console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; } } - if (!(player.getVideoData() && player.getVideoData().isLive)) - { player.setPlaybackRate(Number(option)); if (!video) { video = { playbackRate: 1 }; }; video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl - if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education ) - && option !== 1) { + if (!(player.getVideoData() && player.getVideoData().isLive)) { + player.setPlaybackRate(Number(option)); if (!video) { video = { playbackRate: 1 }; }; video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl + if ((this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education) + && option !== 1) { ImprovedTube.speedException = function () { - if (this.storage.player_dont_speed_education && DATA.genre === 'Education') - {player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return;} - if (this.storage.player_force_speed_on_music ){ + if (this.storage.player_dont_speed_education && DATA.genre === 'Education') { player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return; } + if (this.storage.player_force_speed_on_music) { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); - return; + return; } if (DATA.keywords && !keywords) { keywords = DATA.keywords.join(', ') || ''; } if (keywords === 'video, sharing, camera phone, video phone, free, upload') { keywords = ''; } @@ -162,47 +160,54 @@ ImprovedTube.playerPlaybackSpeed = function () { 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}} + 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? + 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' + 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' + && 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) - && 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?"); } + && 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 // - 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;} + 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); + 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); }); } } @@ -212,53 +217,79 @@ ImprovedTube.playerPlaybackSpeed = function () { 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; + // 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() ) - { 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;} + } catch { } + } + if (DATA.title === ImprovedTube.videoTitle()) { + keywords = document.getElementsByTagName('meta')?.keywords?.content || ''; + if (!keywords) { // <- Remove this + keyword = '' } - 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 = ''; } - })(); + 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) { + 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.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 () {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 = '' + 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; } - 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) { @@ -305,7 +336,7 @@ ImprovedTube.subtitlesLanguage = function () { let subtitlesState; if (option && player && player.getOption && player.setOption && player.isSubtitlesOn && player.toggleSubtitles) { - const matchedTrack = player.getOption('captions', 'tracklist', {includeAsr: true})?.find(track => track.languageCode.includes(option) && (!track.vss_id.includes("a.") || this.storage.auto_generate)); + const matchedTrack = player.getOption('captions', 'tracklist', { includeAsr: true })?.find(track => track.languageCode.includes(option) && (!track.vss_id.includes("a.") || this.storage.auto_generate)); if (matchedTrack) { subtitlesState = player.isSubtitlesOn(); @@ -339,16 +370,16 @@ default = { ------------------------------------------------------------------------------*/ ImprovedTube.subtitlesUserSettings = function () { const ourSettings = { - fontFamily: this.storage.subtitles_font_family, - color: this.storage.subtitles_font_color, - fontSizeIncrement: this.storage.subtitles_font_size, - background: this.storage.subtitles_background_color, - backgroundOpacity: this.storage.subtitles_background_opacity, - windowColor: this.storage.subtitles_window_color, - windowOpacity: this.storage.subtitles_window_opacity, - charEdgeStyle: this.storage.subtitles_character_edge_style, - textOpacity: this.storage.subtitles_font_opacity - }, + fontFamily: this.storage.subtitles_font_family, + color: this.storage.subtitles_font_color, + fontSizeIncrement: this.storage.subtitles_font_size, + background: this.storage.subtitles_background_color, + backgroundOpacity: this.storage.subtitles_background_opacity, + windowColor: this.storage.subtitles_window_color, + windowOpacity: this.storage.subtitles_window_opacity, + charEdgeStyle: this.storage.subtitles_character_edge_style, + textOpacity: this.storage.subtitles_font_opacity + }, userSettings = Object.keys(ourSettings).filter(e => ourSettings[e]), player = this.elements.player; @@ -430,7 +461,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(); } @@ -457,7 +488,7 @@ AUTO FULLSCREEN ------------------------------------------------------------------------------*/ ImprovedTube.playerAutofullscreen = function () { if ( - this.storage.player_autofullscreen && + this.storage.player_autofullscreen && document.documentElement.dataset.pageType === 'video' && !document.fullscreenElement ) { @@ -473,7 +504,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++) { @@ -524,10 +555,10 @@ BATTERY FEATURES; PLAYER QUALITY BASED ON POWER STATUS ------------------------------------------------------------------------------*/ ImprovedTube.batteryFeatures = async function () { if (ImprovedTube.storage.qualityWhenRunningOnBattery - || ImprovedTube.storage.pauseWhileIUnplugTheCharger - || ImprovedTube.storage.whenBatteryIslowDecreaseQuality) { - const updateQuality = async (battery, charging) => { - if (battery) { + || ImprovedTube.storage.pauseWhileIUnplugTheCharger + || ImprovedTube.storage.whenBatteryIslowDecreaseQuality) { + const updateQuality = async (battery, charging) => { + if (battery) { if (!battery.charging) { if (ImprovedTube.storage.pauseWhileIUnplugTheCharger && charging) { ImprovedTube.elements.player.pauseVideo(); @@ -565,7 +596,7 @@ ImprovedTube.batteryFeatures = async function () { FORCED VOLUME ------------------------------------------------------------------------------*/ ImprovedTube.playerVolume = function () { - if (this.storage.player_forced_volume ) { + if (this.storage.player_forced_volume) { var volume = this.storage.player_volume; if (!this.isset(volume)) { @@ -591,7 +622,7 @@ 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; } } @@ -619,7 +650,7 @@ ImprovedTube.playerLoudnessNormalization = function () { try { var local_storage = localStorage['yt-player-volume']; - if (this.isset(Number(this.storage.player_volume)) && this.storage.player_forced_volume ) { + if (this.isset(Number(this.storage.player_volume)) && this.storage.player_forced_volume) { return; } else if (local_storage) { local_storage = JSON.parse(JSON.parse(local_storage).data); @@ -629,7 +660,7 @@ ImprovedTube.playerLoudnessNormalization = function () { } else { video.volume = 100; } - } catch (err) {} + } catch (err) { } } }; /*------------------------------------------------------------------------------ @@ -648,7 +679,7 @@ 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); } @@ -703,7 +734,7 @@ ImprovedTube.renderSubtitle = function (ctx, captionElements) { }; ImprovedTube.playerScreenshotButton = function () { - if (this.storage.player_screenshot_button ) { + if (this.storage.player_screenshot_button) { var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); @@ -729,30 +760,30 @@ ImprovedTube.playerRepeat = 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); + //ImprovedTube.elements.buttons['it-repeat-styles'].style.opacity = '1'; //old class from version 3.x? that both repeat buttons could have + }, 200); } /*------------------------------------------------------------------------------ REPEAT BUTTON ------------------------------------------------------------------------------*/ ImprovedTube.playerRepeatButton = function () { - if (this.storage.player_repeat_button ) { + if (this.storage.player_repeat_button) { var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); 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 ) { transparentOrOn = 1; } + var transparentOrOn = 0.5; if (this.storage.player_always_repeat) { transparentOrOn = 1; } this.createPlayerButton({ id: 'it-repeat-button', child: svg, 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 ) { + if (ImprovedTube.storage.below_player_loop) { var otherButton = document.querySelector('#it-below-player-loop'); otherButton.children[0].style.opacity = opacity; } @@ -773,7 +804,7 @@ ImprovedTube.playerRepeatButton = function () { ROTATE ------------------------------------------------------------------------------*/ ImprovedTube.playerRotateButton = function () { - if (this.storage.player_rotate_button ) { + if (this.storage.player_rotate_button) { var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); @@ -827,26 +858,27 @@ ImprovedTube.playerRotateButton = function () { FIT-TO-WIN BUTTON ------------------------------------------------------------------------------*/ ImprovedTube.playerFitToWinButton = function () { - if (this.storage.player_fit_to_win_button && (/watch\?/.test(location.href))) { - let tempContainer = document.createElement("div"); - let svg; - if (typeof trustedTypes !== 'undefined' && typeof trustedTypes.createPolicy === 'function') { - // Create a Trusted Type policy - const policy = trustedTypes.createPolicy('default', { - createHTML: (string) => string, - }); + if (this.storage.player_fit_to_win_button && (/watch\?/.test(location.href))) { + let tempContainer = document.createElement("div"); + let svg; + if (typeof trustedTypes !== 'undefined' && typeof trustedTypes.createPolicy === 'function') { + // Create a Trusted Type policy + const policy = trustedTypes.createPolicy('default', { + createHTML: (string) => string, + }); - // Use the policy to set innerHTML - tempContainer.innerHTML = policy.createHTML(` + // Use the policy to set innerHTML + tempContainer.innerHTML = policy.createHTML(` `); - // Ensure the SVG element is correctly parsed - svg = tempContainer.querySelector('svg'); - } else { - tempContainer.innerHTML = ` + // Ensure the SVG element is correctly parsed + svg = tempContainer.querySelector('svg'); + } else { + tempContainer.innerHTML = ` `; - svg = tempContainer.firstChild;} + svg = tempContainer.firstChild; + } this.createPlayerButton({ id: 'it-fit-to-win-player-button', child: svg, @@ -873,14 +905,14 @@ 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++ ) { - result.push( nodesSnapshot.snapshotItem(i) ); + var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (var i = 0; i < nodesSnapshot.snapshotLength; i++) { + result.push(nodesSnapshot.snapshotItem(i)); } return result; } -function createOverlay () { +function createOverlay() { var overlay = document.createElement('div'); overlay.id = 'overlay_cinema'; overlay.style.position = 'fixed'; @@ -954,7 +986,7 @@ ImprovedTube.playerCinemaModeEnable = function () { if ((/watch\?/.test(location.href))) { var overlay = document.getElementById('overlay_cinema'); - if (this.storage.player_auto_cinema_mode && !overlay) { + if (this.storage.player_auto_cinema_mode && !overlay) { createOverlay(); overlay = document.getElementById('overlay_cinema'); } @@ -976,7 +1008,7 @@ ImprovedTube.playerCinemaModeEnable = function () { HAMBURGER MENU ------------------------------------------------------------------------------*/ ImprovedTube.playerHamburgerButton = function () { - if (this.storage.player_hamburger_button ) { + if (this.storage.player_hamburger_button) { const videoPlayer = document.querySelector('.html5-video-player'); if (!videoPlayer) { @@ -1030,7 +1062,7 @@ ImprovedTube.playerHamburgerButton = function () { POPUP PLAYER ------------------------------------------------------------------------------*/ ImprovedTube.playerPopupButton = function () { - if (this.storage.player_popup_button && location.href.indexOf('youtube.com/embed') === -1 ) { + if (this.storage.player_popup_button && 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'); @@ -1050,7 +1082,7 @@ ImprovedTube.playerPopupButton = function () { const videoID = location.search.match(ImprovedTube.regex.video_id)[1], listMatch = location.search.match(ImprovedTube.regex.playlist_id), popup = window.open( - `${location.protocol}//www.youtube.com/embed/${videoID}?start=${parseInt(ytPlayer.getCurrentTime())}&autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}${listMatch?`&list=${listMatch[1]}`:''}`, + `${location.protocol}//www.youtube.com/embed/${videoID}?start=${parseInt(ytPlayer.getCurrentTime())}&autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}${listMatch ? `&list=${listMatch[1]}` : ''}`, '_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}` ); @@ -1061,7 +1093,7 @@ ImprovedTube.playerPopupButton = function () { //~ check if the video ID in the link of the video title matches the original video ID in the URL and if not remove the playlist from the URL (reloads the page). const videoLink = this.document.querySelector('div#player div.ytp-title-text>a[href]'); if (videoLink && videoLink.href.match(ImprovedTube.regex.video_id)[1] !== videoID) this.location.search = this.location.search.replace(/(\?)list=[^&]+&|&list=[^&]+/, '$1'); - }, {passive: true, once: true}); + }, { passive: true, once: true }); } //~ change focused tab to URL-less popup ImprovedTube.messages.send({ @@ -1079,7 +1111,7 @@ ImprovedTube.playerPopupButton = function () { Force SDR ------------------------------------------------------------------------------*/ ImprovedTube.playerSDR = function () { - if (this.storage.player_SDR ) { + if (this.storage.player_SDR) { Object.defineProperty(window.screen, 'pixelDepth', { enumerable: true, configurable: true, @@ -1173,7 +1205,7 @@ ImprovedTube.miniPlayer_scroll = function () { window.addEventListener('mousemove', ImprovedTube.miniPlayer_cursorUpdate); window.dispatchEvent(new Event('resize')); - } else if (window.scrollY < 256 && ImprovedTube.mini_player__mode || ImprovedTube.elements.player.classList.contains('ytp-player-minimized') ) { + } else if (window.scrollY < 256 && ImprovedTube.mini_player__mode || ImprovedTube.elements.player.classList.contains('ytp-player-minimized')) { ImprovedTube.mini_player__mode = false; ImprovedTube.elements.player.classList.remove('it-mini-player'); ImprovedTube.mini_player__move = false; @@ -1196,7 +1228,7 @@ ImprovedTube.miniPlayer_mouseDown = function (event) { return false; } - if (ImprovedTube.miniPlayer_resize() ) { + if (ImprovedTube.miniPlayer_resize()) { return false; } @@ -1204,7 +1236,7 @@ ImprovedTube.miniPlayer_mouseDown = function (event) { path = event.composedPath(); for (var i = 0, l = path.length; i < l; i++) { - if ((path[i].classList && path[i].classList.contains('it-mini-player')) ) { + if ((path[i].classList && path[i].classList.contains('it-mini-player'))) { is_player = true; } } @@ -1424,7 +1456,7 @@ ImprovedTube.miniPlayer_resizeMouseUp = function () { }; ImprovedTube.miniPlayer = function () { - if (this.storage.mini_player ) { + if (this.storage.mini_player) { var data = localStorage.getItem('improvedtube-mini-player'); try { @@ -1478,12 +1510,12 @@ ImprovedTube.miniPlayer = function () { CUSTOM PAUSE FUNCTIONS ------------------------------------------------------------------------------*/ ImprovedTube.pauseWhileTypingOnYoutube = function () { - if (ImprovedTube.storage.pause_while_typing_on_youtube ) { + if (ImprovedTube.storage.pause_while_typing_on_youtube) { var timeoutId; // Declare a variable to hold the timeout ID // 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 + // Check on the storage for pause_while_typing_on_youtube_storage is false // If player is NOT in the viewport, return if (!isPlayerInViewport()) { @@ -1495,10 +1527,10 @@ ImprovedTube.pauseWhileTypingOnYoutube = function () { 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" )) { - // Pause the video - // Check if player is paused + !(e.ctrlKey && (e.key === "c" || e.key === "x" || e.key === "a")) && + (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(); } @@ -1516,7 +1548,7 @@ ImprovedTube.pauseWhileTypingOnYoutube = function () { } }); - function isPlayerInViewport () { + function isPlayerInViewport() { var player = ImprovedTube.elements.player; if (player) { var rect = player.getBoundingClientRect(); @@ -1526,9 +1558,9 @@ ImprovedTube.pauseWhileTypingOnYoutube = function () { // Check if the player is in the viewport return ( rect.top != 0 && - rect.left != 0 && - rect.bottom <= windowHeight && - rect.right <= windowWidth + rect.left != 0 && + rect.bottom <= windowHeight && + rect.right <= windowWidth ); } 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 93c8c253e..c71d8a8de 100644 --- a/js&css/web-accessible/www.youtube.com/playlist.js +++ b/js&css/web-accessible/www.youtube.com/playlist.js @@ -4,12 +4,13 @@ /*------------------------------------------------------------------------------ 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 - && playlistData.currentIndex - && playlistData.totalVideos - && playlistData.localCurrentIndex) { +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; } } @@ -18,8 +19,8 @@ ImprovedTube.playlistUpNextAutoplay = function () { if (this.storage.playlist_up 4.5.2 REVERSE ------------------------------------------------------------------------------*/ ImprovedTube.playlistReverse = function () { - if (this.storage.playlist_reverse ) { - function update () { + if (this.storage.playlist_reverse) { + function update() { var results = ImprovedTube.elements.ytd_watch.data.contents.twoColumnWatchNextResults, playlist = results.playlist.playlist, autoplay = results.autoplay.autoplay; @@ -81,7 +82,7 @@ ImprovedTube.playlistReverse = function () { ImprovedTube.elements.playlist.actions.appendChild(button); } - if (this.playlistReversed ) { + if (this.playlistReversed) { update(); } } @@ -91,17 +92,16 @@ ImprovedTube.playlistReverse = function () { 4.5.3 REPEAT ------------------------------------------------------------------------------*/ ImprovedTube.playlistRepeat = function () { - if ( ImprovedTube.storage.playlist_repeat ) { - setTimeout(function () { + if (ImprovedTube.storage.playlist_repeat) { + 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 && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M21') + if (button && (option && 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.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); } }; @@ -112,14 +112,13 @@ ImprovedTube.playlistRepeat = function () { 4.5.4 SHUFFLE ------------------------------------------------------------------------------*/ ImprovedTube.playlistShuffle = function () { - if ( ImprovedTube.storage.playlist_shuffle ) { + if (ImprovedTube.storage.playlist_shuffle) { 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 && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M18.1') - ) ) - { button.click(); } + if (button && (option && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M18.1') + )) { button.click(); } }, 10000); } }; @@ -171,7 +170,7 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c //~ check if the video ID in the link of the video title matches the original video ID in the URL and if not reload as a videoseries/playlist (without the videoID and start-time). const videoLink = this.document.querySelector('div#player div.ytp-title-text>a[href]'); if (videoLink && videoLink.href.match(ImprovedTube.regex.video_id)[1] !== videoID) this.location.href = `${location.protocol}//www.youtube.com/embed/videoseries?autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}&list=${listID}`; - }, {passive: true, once: true}); + }, { passive: true, once: true }); } else 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 ImprovedTube.messages.send({ @@ -183,12 +182,12 @@ 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 @@ -223,7 +222,7 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c */ ImprovedTube.playlistPopup = function () { "use strict"; - if (this.storage.playlist_popup ) { + if (this.storage.playlist_popup) { const playlistID = location.search.match(this.regex.playlist_id)?.[1], playlistIDMini = this.elements.player?.getPlaylistId?.(); @@ -245,6 +244,6 @@ ImprovedTube.playlistPopup = 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 7771cfb3e..6409407de 100644 --- a/js&css/web-accessible/www.youtube.com/settings.js +++ b/js&css/web-accessible/www.youtube.com/settings.js @@ -24,7 +24,6 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { var label = document.createElement('span'); button = document.createElement('button'); - button.className = 'it-button'; button.addEventListener('mousedown', function (event) { @@ -32,7 +31,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,23 +43,20 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { button.style.top = y + 'px'; } - function mouseup () { - localStorage.setItem('improvedtube-button-position', JSON.stringify({x, y})); - + 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); } window.addEventListener('mousemove', mousemove); window.addEventListener('mouseup', mouseup); window.addEventListener('click', click); - event.preventDefault(); } }); @@ -95,7 +91,7 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { document.body.appendChild(scrim); document.body.appendChild(iframe); - ImprovedTube.messages.send({requestOptionsUrl: true}); + ImprovedTube.messages.send({ requestOptionsUrl: true }); } }); @@ -159,7 +155,7 @@ 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 a1f918f0a..ad85a0697 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -34,7 +34,7 @@ ImprovedTube.shortcutsInit = function () { case 'keys': // set of unique scancodes - potentialShortcut[button] = keys[button] ? new Set(Object.keys(keys[button]).map(s=>Number(s))) : new Set(); + potentialShortcut[button] = keys[button] ? new Set(Object.keys(keys[button]).map(s => Number(s))) : new Set(); break } } @@ -46,7 +46,7 @@ ImprovedTube.shortcutsInit = function () { // only one listener per handle if (!listeners[name]) { listeners[name] = true; - window.addEventListener(name, handler, {passive: false, capture: true}); + window.addEventListener(name, handler, { passive: false, capture: true }); } } } else { @@ -54,7 +54,7 @@ ImprovedTube.shortcutsInit = function () { for (const [name, handler] of Object.entries(this.shortcutsListeners)) { if (listeners[name]) { delete listeners[name]; - window.removeEventListener(name, handler, {passive: false, capture: true}); + window.removeEventListener(name, handler, { passive: false, capture: true }); } } } @@ -344,12 +344,13 @@ ImprovedTube.shortcutIncreasePlaybackSpeed = function (decrease) { } if (decrease) { // Slow down near 0 // Chrome's minimum is 0.0625. Otherwise this could seamlessly turn into single frame steps. - newSpeed = (speed - value < 0.1) ? Math.max(Number(speed*0.7).toFixed(2),0.0625) : (speed - value); + newSpeed = (speed - value < 0.1) ? Math.max(Number(speed * 0.7).toFixed(2), 0.0625) : (speed - value); } else { // Aligning at 1.0 instead of passing by 1: - if (speed < 1 && speed > 1-ImprovedTube.storage.shortcuts_playback_speed_step ) {newSpeed = 1; - // Firefox doesnt limit speed to 16x, we can allow more in Firefox. - } else { newSpeed = (speed + value > 16) ? 16 : (speed + value); } + if (speed < 1 && speed > 1 - ImprovedTube.storage.shortcuts_playback_speed_step) { + newSpeed = 1; + // Firefox doesnt limit speed to 16x, we can allow more in Firefox. + } else { newSpeed = (speed + value > 16) ? 16 : (speed + value); } } newSpeed = this.playbackSpeed(newSpeed); if (!newSpeed) { @@ -363,7 +364,7 @@ ImprovedTube.shortcutIncreasePlaybackSpeed = function (decrease) { ------------------------------------------------------------------------------*/ ImprovedTube.shortcutDecreasePlaybackSpeed = function () { ImprovedTube.shortcutIncreasePlaybackSpeed(true); -}; +}; /*------------------------------------------------------------------------------ 4.7.18 RESET PLAYBACK SPEED ------------------------------------------------------------------------------*/ @@ -449,29 +450,37 @@ ImprovedTube.shortcutReport = function () { }, 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 { + 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 failed2"); - document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); - }}, 800); - }}, 200); + 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 { + setTimeout(function () { + try { document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1) } catch { - console.log("dropdown visible failed2"); - }}, 1700); - }}, 700); + 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 @@ -485,9 +494,9 @@ ImprovedTube.shortcutSubscribe = function () { ImprovedTube.shortcutDarkTheme = function () { if (document.documentElement.hasAttribute('dark')) { // message will propagate all the way to setTheme() so we dont need to do anything more here - ImprovedTube.messages.send({action: 'set', key: 'theme', value: 'light'}); + ImprovedTube.messages.send({ action: 'set', key: 'theme', value: 'light' }); } else { - ImprovedTube.messages.send({action: 'set', key: 'theme', value: 'dark'}); + ImprovedTube.messages.send({ action: 'set', key: 'theme', value: 'dark' }); } }; /*------------------------------------------------------------------------------ @@ -504,7 +513,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); }; @@ -539,7 +548,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 7763f229f..f4151445e 100644 --- a/js&css/web-accessible/www.youtube.com/themes.js +++ b/js&css/web-accessible/www.youtube.com/themes.js @@ -23,52 +23,52 @@ ImprovedTube.myColors = function () { 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;' + - '--yt-spec-brand-background-secondary:rgba(0,0,0, 0.1) !important;' + - '--yt-spec-badge-chip-background:rgba(0, 0, 0, 0.05) !important;' + - '--yt-spec-verified-badge-background:rgba(0, 0, 0, 0.15) !important;' + - '--yt-spec-button-chip-background-hover:rgba(0, 0, 0, 0.10) !important;' + - '--yt-spec-brand-button-background:rgba(136,136,136,1) !important;' + - '--yt-spec-filled-button-focus-outline:rgba(0, 0, 0, 0.60) !important;' + - '--yt-spec-call-to-action-button-focus-outline:rgba(0,0,0, 0.30) !important;' + - '--yt-spec-brand-text-button-focus-outline:rgba(204, 0, 0, 0.30) !important;' + - '--yt-spec-10-percent-layer:rgba(136,136,136,1) !important;' + - '--yt-swatch-primary:' + primary_color + '!important;' + - '--yt-swatch-primary-darker:' + primary_color + '!important;' + - '--yt-spec-brand-background-solid:' + primary_color + '!important;' + - '--yt-spec-general-background-a:' + primary_color + '!important;' + - '--yt-spec-general-background-b:' + primary_color + '!important;' + - '--yt-spec-general-background-c:' + primary_color + '!important;' + - '--yt-spec-touch-response:' + primary_color + '!important;' + - '--yt-swatch-text: ' + text_color + '!important;' + - '--yt-swatch-important-text: ' + text_color + '!important;' + - '--yt-swatch-input-text: ' + text_color + '!important;' + - '--yt-swatch-logo-override: ' + text_color + '!important;' + - '--yt-spec-text-primary:' + text_color + ' !important;' + - '--yt-spec-text-primary-inverse:' + primary_color + ' !important;' + - '--yt-spec-text-secondary:' + text_color + ' !important;' + - '--yt-spec-text-disabled:' + text_color + ' !important;' + - '--yt-spec-icon-active-other:' + text_color + ' !important;' + - '--yt-spec-icon-inactive:' + text_color + ' !important;' + - '--yt-spec-icon-disabled:' + text_color + ' !important;' + - '--yt-spec-filled-button-text:' + text_color + ' !important;' + - '--yt-spec-call-to-action-inverse:' + text_color + ' !important;' + - '--yt-spec-brand-icon-active:' + text_color + ' !important;' + - '--yt-spec-brand-icon-inactive:' + text_color + ' !important;' + - '--yt-spec-brand-link-text:' + text_color + '!important;' + - '--yt-spec-brand-subscribe-button-background:' + text_color + ' !important;' + - '--yt-spec-wordmark-text:' + text_color + ' !important;' + - '--yt-spec-selected-nav-text:' + text_color + ' !important;' + - '--yt-spec-base-background:' + primary_color + '!important;' + - '--yt-spec-raised-background:' + primary_color + '!important;' + - '--yt-spec-menu-background:' + primary_color + '!important;' + - '--yt-spec-inverted-background: #fff;' + - '--ytd-searchbox-background:' + primary_color + '!important;' + - '--ytd-searchbox-legacy-button-color:' + 'var(--yt-spec-brand-background-primary)' + '!important;' + - 'background-color: var(--yt-spec-base-background)!important;' + - '}'; + '--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;' + + '--yt-spec-brand-background-secondary:rgba(0,0,0, 0.1) !important;' + + '--yt-spec-badge-chip-background:rgba(0, 0, 0, 0.05) !important;' + + '--yt-spec-verified-badge-background:rgba(0, 0, 0, 0.15) !important;' + + '--yt-spec-button-chip-background-hover:rgba(0, 0, 0, 0.10) !important;' + + '--yt-spec-brand-button-background:rgba(136,136,136,1) !important;' + + '--yt-spec-filled-button-focus-outline:rgba(0, 0, 0, 0.60) !important;' + + '--yt-spec-call-to-action-button-focus-outline:rgba(0,0,0, 0.30) !important;' + + '--yt-spec-brand-text-button-focus-outline:rgba(204, 0, 0, 0.30) !important;' + + '--yt-spec-10-percent-layer:rgba(136,136,136,1) !important;' + + '--yt-swatch-primary:' + primary_color + '!important;' + + '--yt-swatch-primary-darker:' + primary_color + '!important;' + + '--yt-spec-brand-background-solid:' + primary_color + '!important;' + + '--yt-spec-general-background-a:' + primary_color + '!important;' + + '--yt-spec-general-background-b:' + primary_color + '!important;' + + '--yt-spec-general-background-c:' + primary_color + '!important;' + + '--yt-spec-touch-response:' + primary_color + '!important;' + + '--yt-swatch-text: ' + text_color + '!important;' + + '--yt-swatch-important-text: ' + text_color + '!important;' + + '--yt-swatch-input-text: ' + text_color + '!important;' + + '--yt-swatch-logo-override: ' + text_color + '!important;' + + '--yt-spec-text-primary:' + text_color + ' !important;' + + '--yt-spec-text-primary-inverse:' + primary_color + ' !important;' + + '--yt-spec-text-secondary:' + text_color + ' !important;' + + '--yt-spec-text-disabled:' + text_color + ' !important;' + + '--yt-spec-icon-active-other:' + text_color + ' !important;' + + '--yt-spec-icon-inactive:' + text_color + ' !important;' + + '--yt-spec-icon-disabled:' + text_color + ' !important;' + + '--yt-spec-filled-button-text:' + text_color + ' !important;' + + '--yt-spec-call-to-action-inverse:' + text_color + ' !important;' + + '--yt-spec-brand-icon-active:' + text_color + ' !important;' + + '--yt-spec-brand-icon-inactive:' + text_color + ' !important;' + + '--yt-spec-brand-link-text:' + text_color + '!important;' + + '--yt-spec-brand-subscribe-button-background:' + text_color + ' !important;' + + '--yt-spec-wordmark-text:' + text_color + ' !important;' + + '--yt-spec-selected-nav-text:' + text_color + ' !important;' + + '--yt-spec-base-background:' + primary_color + '!important;' + + '--yt-spec-raised-background:' + primary_color + '!important;' + + '--yt-spec-menu-background:' + primary_color + '!important;' + + '--yt-spec-inverted-background: #fff;' + + '--ytd-searchbox-background:' + primary_color + '!important;' + + '--ytd-searchbox-legacy-button-color:' + 'var(--yt-spec-brand-background-primary)' + '!important;' + + 'background-color: var(--yt-spec-base-background)!important;' + + '}'; this.elements.my_colors = style; document.documentElement.appendChild(style); @@ -86,16 +86,16 @@ ImprovedTube.setTheme = function () { document.documentElement.setAttribute('dark', ''); document.querySelector('ytd-masthead')?.setAttribute('dark', ''); ImprovedTube.setPrefCookieValueByName('f6', 400); - // fall through + // 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.messages.send({ action: 'set', key: 'theme', value: null }); ImprovedTube.setPrefCookieValueByName('f6', null); - // fall through + // fall through case 'dawn': case 'sunset': case 'night': diff --git a/menu/functions.js b/menu/functions.js index 6dff508a1..145b72473 100644 --- a/menu/functions.js +++ b/menu/functions.js @@ -188,7 +188,7 @@ extension.pushSettings = function () { try { chrome.storage.sync.clear(); var blob = JSON.stringify(satus.storage.data); - chrome.storage.sync.set({settings: blob}); + chrome.storage.sync.set({ settings: blob }); } catch (error) { console.error(error); } diff --git a/menu/index.js b/menu/index.js index 24238322a..ea19c8e11 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);