From be504b763f02106493f5a4bb6e78dd00aac83ae5 Mon Sep 17 00:00:00 2001 From: ImprovedTube Date: Mon, 8 Jul 2024 01:14:15 +0200 Subject: [PATCH] keep'm one-liners --- background.js | 17 +- {.github/workflows => build}/crowdin.yml | 0 js&css/extension/functions.js | 5 +- js&css/extension/init.js | 13 +- .../www.youtube.com/general/general.js | 37 +- .../www.youtube.com/night-mode/night-mode.js | 12 +- js&css/web-accessible/core.js | 27 +- js&css/web-accessible/functions.js | 119 ++--- js&css/web-accessible/init.js | 20 +- .../www.youtube.com/appearance.js | 304 +++++------ .../web-accessible/www.youtube.com/channel.js | 13 +- .../web-accessible/www.youtube.com/player.js | 494 +++++++----------- .../www.youtube.com/playlist.js | 43 +- .../www.youtube.com/settings.js | 7 +- .../www.youtube.com/shortcuts.js | 78 +-- menu/index.js | 4 +- menu/satus.js | 32 +- menu/skeleton-parts/appearance.js | 37 +- menu/skeleton-parts/general.js | 14 +- 19 files changed, 469 insertions(+), 807 deletions(-) rename {.github/workflows => build}/crowdin.yml (100%) diff --git a/background.js b/background.js index 04768c8b1..b147d6650 100644 --- a/background.js +++ b/background.js @@ -95,15 +95,13 @@ chrome.runtime.onInstalled.addListener(function (installed) { }); } else if (installed.reason == 'install') { if (navigator.userAgent.indexOf("Firefox") != -1) { - chrome.storage.local.set({below_player_pip: false}) - } + chrome.storage.local.set({below_player_pip: false})} if (navigator.userAgent.indexOf('Safari') !== -1 && (!/Windows|Chrom/.test(navigator.userAgent) || /Macintosh|iPhone/.test(navigator.userAgent))) { chrome.storage.local.set({below_player_pip: false}) // still needed? (are screenshots broken in Safari?): - chrome.storage.local.set({below_player_screenshot: false}) - } + chrome.storage.local.set({below_player_screenshot: false})} // console.log('Thanks for installing!'); } }); @@ -282,18 +280,14 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { top: 20 } - if (tID) { - data.tabId = tID; - } + if (tID) {data.tabId = tID;} chrome.windows.create(data); //append to title? chrome.tabs.onUpdated.addListener(function listener (tabId, changeInfo) { if (tabId === tID && changeInfo.status === 'complete' && !message.title.startsWith("undefined")) { chrome.tabs.onUpdated.removeListener(listener); - chrome.scripting.executeScript({ target: { tabId: tID }, func: () => { - document.title = `${message.title} - ImprovedTube`; - } }); //manifest3 + chrome.scripting.executeScript({ target: { tabId: tID }, func: () => { document.title = `${message.title} - ImprovedTube`; } }); //manifest3 // chrome.tabs.executeScript(tID, {code: `document.title = "${message.title} - ImprovedTube";`}); //manifest2 } }); @@ -320,8 +314,7 @@ chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { } } else { console.error('Permission is not granted.'); - } - }) + }}) break } }); diff --git a/.github/workflows/crowdin.yml b/build/crowdin.yml similarity index 100% rename from .github/workflows/crowdin.yml rename to build/crowdin.yml diff --git a/js&css/extension/functions.js b/js&css/extension/functions.js index a3c828437..cc7ac242e 100644 --- a/js&css/extension/functions.js +++ b/js&css/extension/functions.js @@ -5,7 +5,4 @@ --------------------------------------------------------------*/ extension.functions.getUrlParameter = function (url, parameter) { var match = url.match(new RegExp('(\\?|\\&)' + parameter + '=[^&]+')); - if (match) { - return match[0].substr(3); - } -}; \ No newline at end of file + if (match) {return match[0].substr(3);}}; \ No newline at end of file diff --git a/js&css/extension/init.js b/js&css/extension/init.js index 91d640531..8020cd839 100644 --- a/js&css/extension/init.js +++ b/js&css/extension/init.js @@ -243,15 +243,6 @@ document.addEventListener('it-message-from-youtube', function () { document.addEventListener('it-play', function (event) { var videos = document.querySelectorAll('video'); - try { - chrome.runtime.sendMessage({action: 'play'}) - } catch (error) { - console.log(error); setTimeout(function () { - try { - chrome.runtime.sendMessage({action: 'play'}, function (response) { - console.log(response) - } ); - } catch { } - }, 321) - } + try {chrome.runtime.sendMessage({action: 'play'})} + catch (error) {console.log(error); setTimeout(function () { try { chrome.runtime.sendMessage({action: 'play'}, function (response) { console.log(response) } ); } catch { } }, 321) } }); diff --git a/js&css/extension/www.youtube.com/general/general.js b/js&css/extension/www.youtube.com/general/general.js index 8413b5a6c..374627927 100644 --- a/js&css/extension/www.youtube.com/general/general.js +++ b/js&css/extension/www.youtube.com/general/general.js @@ -170,9 +170,7 @@ extension.features.addScrollToTop = function (event) { path.setAttribute('d', 'M13 19V7.8l4.9 5c.4.3 1 .3 1.4 0 .4-.5.4-1.1 0-1.5l-6.6-6.6a1 1 0 0 0-1.4 0l-6.6 6.6a1 1 0 1 0 1.4 1.4L11 7.8V19c0 .6.5 1 1 1s1-.5 1-1z'); svg.appendChild(path); this.addScrollToTop.button.appendChild(svg); - window.addEventListener('scroll', function () { - document.body.appendChild(extension.features.addScrollToTop.button); - }); + window.addEventListener('scroll', function () { document.body.appendChild(extension.features.addScrollToTop.button); }); this.addScrollToTop.button.addEventListener('click', function () { window.scrollTo(0, 0); document.getElementById('it-scroll-to-top')?.remove(); @@ -251,30 +249,15 @@ extension.features.popupWindowButtons = function (event) { target.itPopupWindowButton.addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); - try { - this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] - } catch (error) { - console.log(error) - }; + try { this.parentElement.itPopupWindowButton.dataset.id = this.parentElement.href.match(/(?:[?&]v=|embed\/|shorts\/)([^&?]{11})/)[1] } catch (error) { console.log(error)}; ytPlayer = document.querySelector("#movie_player"); - if (ytPlayer) { - width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65 - } else { - width = innerWidth * 0.4; height = innerHeight * 0.4; - } + if (ytPlayer) {width = ytPlayer.offsetWidth * 0.65; height = ytPlayer.offsetHeight * 0.65} + else { width = innerWidth * 0.4; height = innerHeight * 0.4; } if (!ytPlayer) { let shorts = /short/.test(this.parentElement.href); - if ( width / height < 1 ) { - let vertical = true - } else { - let vertical = false - } - if ( !vertical && shorts ) { - width = height * 0.6 - } - if ( vertical && !shorts ) { - height = width * 0.6 - } + if ( width / height < 1 ) { let vertical = true } else { let vertical = false } + if ( !vertical && shorts ) { width = height * 0.6} + if ( vertical && !shorts ) { height = width * 0.6} } window.open('https://www.youtube.com/embed/' + this.dataset.id + '?autoplay=' + (extension.storage.get('player_autoplay_disable') ? '0' : '1'), '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); @@ -373,8 +356,7 @@ extension.features.markWatchedVideos = function (anything) { target.itMarkWatchedVideosButton.appendChild(svg); target.itMarkWatchedVideosButton.appendChild(svg2); if (extension.storage.get('watched') && extension.storage.get('watched')[id]) { - target.itMarkWatchedVideosButton.setAttribute('watched', '') - }; + target.itMarkWatchedVideosButton.setAttribute('watched', '')}; target.appendChild(target.itMarkWatchedVideosButton); target.itMarkWatchedVideosButton.addEventListener('click', function (event) { var id = this.dataset.id, @@ -397,8 +379,7 @@ extension.features.markWatchedVideos = function (anything) { chrome.storage.local.set({ watched: extension.storage.get('watched') - }); - }); + });}); } else { var button = target.itMarkWatchedVideosButton; diff --git a/js&css/extension/www.youtube.com/night-mode/night-mode.js b/js&css/extension/www.youtube.com/night-mode/night-mode.js index d729a0fd4..084a4e843 100644 --- a/js&css/extension/www.youtube.com/night-mode/night-mode.js +++ b/js&css/extension/www.youtube.com/night-mode/night-mode.js @@ -82,16 +82,10 @@ extension.features.bluelight = function () { extension.features.dim = function () { var value = extension.storage.get('dim'); - if (extension.features.schedule() === false) { - return false; - } + if (extension.features.schedule() === false) { return false;} - if (!value) { - value = 0; - } - if (typeof value !== 'number') { - value = Number(value); - } + if (!value) { value = 0;} + if (typeof value !== 'number') {value = Number(value);} if (value !== 0) { if (!this.dim.element) { var element = document.createElement('div'); diff --git a/js&css/web-accessible/core.js b/js&css/web-accessible/core.js index d2df7d826..446edc86a 100644 --- a/js&css/web-accessible/core.js +++ b/js&css/web-accessible/core.js @@ -181,8 +181,7 @@ document.addEventListener('it-message-from-extension', function () { if (ImprovedTube.storage.block_vp9 || ImprovedTube.storage.block_av1 || ImprovedTube.storage.block_h264) { let atlas = {block_vp9:'vp9|vp09', block_h264:'avc1', block_av1:'av01'}, codec = Object.keys(atlas).reduce(function (all, key) { - return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all - }, ''); + return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all}, ''); if (localStorage['it-codec'] != codec) { localStorage['it-codec'] = codec; } @@ -208,8 +207,7 @@ document.addEventListener('it-message-from-extension', function () { if (['block_vp9', 'block_h264', 'block_av1'].includes(message.key)) { let atlas = {block_vp9:'vp9|vp09', block_h264:'avc1', block_av1:'av01'} localStorage['it-codec'] = Object.keys(atlas).reduce(function (all, key) { - return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all - }, ''); + return ImprovedTube.storage[key] ? ((all?all+'|':'') + atlas[key]) : all}, ''); if (!localStorage['it-codec']) { localStorage.removeItem('it-codec'); } @@ -248,13 +246,9 @@ document.addEventListener('it-message-from-extension', function () { case 'description': if (ImprovedTube.storage.description === "expanded" || ImprovedTube.storage.description === "classic_expanded") { - try { - document.querySelector("#more").click() || document.querySelector("#expand").click(); - } catch {} + try {document.querySelector("#more").click() || document.querySelector("#expand").click();} catch {} } else if (ImprovedTube.storage.description === "normal" || ImprovedTube.storage.description === "classic") { - try { - document.querySelector("#less").click() || document.querySelector("#collapse").click(); - } catch {} + try {document.querySelector("#less").click() || document.querySelector("#collapse").click();} catch {} } break @@ -288,9 +282,7 @@ document.addEventListener('it-message-from-extension', function () { const button = ImprovedTube.elements.player.querySelector("button.ytp-size-button"); if (button && ImprovedTube.elements.ytd_watch.theater === true) { ImprovedTube.elements.ytd_watch.theater = false; - setTimeout(function () { - button.click(); - }, 100); + setTimeout(function () { button.click();}, 100); } } break @@ -404,10 +396,7 @@ document.addEventListener('it-message-from-extension', function () { break case 'playerlistUpNextAutoplay': if (this.storage.playlist_up_next_autoplay !== false) { - if (playlistData.currentIndex != playlistData.localCurrentIndex) { - playlistData.currentIndex = playlistData.localCurrentIndex; - } - } + if (playlistData.currentIndex != playlistData.localCurrentIndex) { playlistData.currentIndex = playlistData.localCurrentIndex;} } break } @@ -415,9 +404,7 @@ document.addEventListener('it-message-from-extension', function () { if (message.key.startsWith('shortcut_')) camelized_key = 'shortcuts'; if (ImprovedTube[camelized_key]) { - try { - ImprovedTube[camelized_key]() - } catch {}; + try {ImprovedTube[camelized_key]()} catch {}; } } else if (message.focus === true && ImprovedTube.elements.player) { ImprovedTube.focus = true; diff --git a/js&css/web-accessible/functions.js b/js&css/web-accessible/functions.js index 6e4441e8f..320bad2d1 100644 --- a/js&css/web-accessible/functions.js +++ b/js&css/web-accessible/functions.js @@ -56,22 +56,11 @@ ImprovedTube.ytElementsHandler = function (node) { if (index === 0) { if (this.storage.playlist_reverse === true) { //can be precise: - try { - this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode; - } catch { - try { - this.elements.playlist.actions = node.parentNode.parentNode.parentNode; - } catch { - try { - this.elements.playlist.actions = node.parentNode.parentNode; - } catch { - try { - this.elements.playlist.actions = node.parentNode; - } catch { - try { - this.elements.playlist.actions = node; - } catch {} - } + try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode;} + catch {try {this.elements.playlist.actions = node;} catch {}} } } } @@ -84,22 +73,11 @@ ImprovedTube.ytElementsHandler = function (node) { if (this.storage.playlist_reverse === true) { //can be precise: - try { - this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode; - } catch { - try { - this.elements.playlist.actions = node.parentNode.parentNode.parentNode; - } catch { - try { - this.elements.playlist.actions = node.parentNode.parentNode; - } catch { - try { - this.elements.playlist.actions = node.parentNode; - } catch { - try { - this.elements.playlist.actions = node; - } catch {} - } + try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode.parentNode;} + catch {try {this.elements.playlist.actions = node.parentNode;} + catch {try {this.elements.playlist.actions = node;} catch {}} } } } @@ -152,7 +130,8 @@ ImprovedTube.ytElementsHandler = function (node) { this.improvedtubeYoutubeIcon(); } - } else if (name === 'TP-YT-APP-DRAWER') { + } + else if (name === 'TP-YT-APP-DRAWER') { if (!this.elements.app_drawer) { this.elements.app_drawer = {start: node.querySelector('div#header'), logo: node.querySelector('a#logo') @@ -247,13 +226,8 @@ ImprovedTube.ytElementsHandler = function (node) { } } else if (document.documentElement.dataset.pageType === 'video') { if (id === 'description-inline-expander' || id === 'description-inner') { - setTimeout(function () { - ImprovedTube.expandDescription(node); - }, 300); - } else if (id === 'meta') { - setTimeout(function () { - ImprovedTube.expandDescription(node.querySelector('#more')); - }, 200); + setTimeout(function () {ImprovedTube.expandDescription(node);}, 300); + } else if (id === 'meta') {setTimeout(function () {ImprovedTube.expandDescription(node.querySelector('#more'));}, 200); } else if (id === 'below') { setTimeout(function () {}, 0); } else if (id === 'panels') { @@ -311,9 +285,7 @@ ImprovedTube.videoPageUpdate = function () { ImprovedTube.upNextAutoplay(); ImprovedTube.playerAutofullscreen(); ImprovedTube.playerSize(); - if (this.storage.player_always_repeat === true) { - ImprovedTube.playerRepeat(); - }; + if (this.storage.player_always_repeat === true) { ImprovedTube.playerRepeat(); }; ImprovedTube.playerScreenshotButton(); ImprovedTube.playerRepeatButton(); ImprovedTube.playerRotateButton(); @@ -370,9 +342,7 @@ ImprovedTube.initPlayer = function () { ImprovedTube.playerQuality(); ImprovedTube.batteryFeatures(); ImprovedTube.playerVolume(); - if (this.storage.player_always_repeat === true) { - ImprovedTube.playerRepeat(); - } + if (this.storage.player_always_repeat === true) { ImprovedTube.playerRepeat(); } ImprovedTube.playerScreenshotButton(); ImprovedTube.playerRepeatButton(); ImprovedTube.playerRotateButton(); @@ -381,12 +351,8 @@ ImprovedTube.initPlayer = function () { ImprovedTube.playerHamburgerButton(); ImprovedTube.playerControls(); ImprovedTube.expandDescription(); - setTimeout(function () { - ImprovedTube.forcedTheaterMode(); - }, 150); - if (location.href.indexOf('/embed/') === -1) { - ImprovedTube.miniPlayer(); - } + setTimeout(function () {ImprovedTube.forcedTheaterMode();}, 150); + if (location.href.indexOf('/embed/') === -1) { ImprovedTube.miniPlayer(); } } }; @@ -408,12 +374,8 @@ ImprovedTube.playerOnTimeUpdate = function () { ImprovedTube.playerQuality(); } - if (ImprovedTube.storage.always_show_progress_bar === true) { - ImprovedTube.showProgressBar(); - } - if (ImprovedTube.storage.player_remaining_duration === true) { - ImprovedTube.playerRemainingDuration(); - } + if (ImprovedTube.storage.always_show_progress_bar === true) {ImprovedTube.showProgressBar();} + if (ImprovedTube.storage.player_remaining_duration === true) {ImprovedTube.playerRemainingDuration();} ImprovedTube.played_time += .5; }, 500); } @@ -425,9 +387,7 @@ ImprovedTube.playerOnTimeUpdate = function () { }; ImprovedTube.playerOnLoadedMetadata = function () { - setTimeout(function () { - ImprovedTube.playerSize(); - }, 100); + setTimeout(function () {ImprovedTube.playerSize();}, 100); }; ImprovedTube.playerOnPause = function (event) { @@ -469,18 +429,14 @@ ImprovedTube.onkeydown = function () { ImprovedTube.onmousedown = function () { window.addEventListener('mousedown', function (event) { if (!ImprovedTube.user_interacted) { - setTimeout(function () { - ImprovedTube.user_interacted = true - }, 3000); + setTimeout(function () {ImprovedTube.user_interacted = true}, 3000); if (ImprovedTube.elements.player && ImprovedTube.elements.player.classList.contains('ad-showing') === false) { var path = event.composedPath(); for (var i = 0, l = path.length; i < l; i++) { if (path[i].className // && path[i].className.indexOf && (/html5-(main-video|video-container)|ytp-play-button/.test(path[i].className)) - ) { - ImprovedTube.user_interacted = true; - } + ) {ImprovedTube.user_interacted = true;} } } } @@ -620,8 +576,7 @@ ImprovedTube.createPlayerButton = function (options) { tooltip.textContent = this.dataset.title; if (this.storage && (this.storage.player_cinema_mode_button || this.storage.player_auto_hide_cinema_mode_when_paused || this.storage.player_auto_cinema_mode)) { - tooltip.style.zIndex = 10001; - } // needed for cinema mode + tooltip.style.zIndex = 10001;} // needed for cinema mode function mouseleave () { tooltip.remove(); @@ -657,14 +612,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'); @@ -682,25 +631,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 efcfd1fc9..628171893 100644 --- a/js&css/web-accessible/init.js +++ b/js&css/web-accessible/init.js @@ -3,9 +3,7 @@ --------------------------------------------------------------*/ ImprovedTube.messages.create(); ImprovedTube.messages.listener(); -if (document.body) { - ImprovedTube.childHandler(document.body); -} +if (document.body) { ImprovedTube.childHandler(document.body); } ImprovedTube.observer = new MutationObserver(function (mutationList) { @@ -107,12 +105,8 @@ ImprovedTube.init = function () { this.onmousedown(); this.youtubeLanguage(); this.myColors(); - if (this.storage.undo_the_new_sidebar === true) { - this.undoTheNewSidebar(); - } - if (this.storage.description === "sidebar") { - this.descriptionSidebar(); - } + if (this.storage.undo_the_new_sidebar === true) {this.undoTheNewSidebar();} + if (this.storage.description === "sidebar") {this.descriptionSidebar();} this.channelCompactTheme(); if (ImprovedTube.elements.player && ImprovedTube.elements.player.setPlaybackRate) { @@ -151,9 +145,7 @@ document.addEventListener('yt-navigate-finish', function () { // if(node.getAttribute('itemprop') === 'uploadDate') {ImprovedTube.uploadDate = node.content;} */ ImprovedTube.pageType(); - if (ImprovedTube.storage.undo_the_new_sidebar) { - ImprovedTube.undoTheNewSidebar(); - } + if (ImprovedTube.storage.undo_the_new_sidebar) { ImprovedTube.undoTheNewSidebar(); } ImprovedTube.commentsSidebar(); if (ImprovedTube.elements.player && ImprovedTube.elements.player.setPlaybackRate) { @@ -182,9 +174,7 @@ window.addEventListener('load', function () { logo: document.querySelector('tp-yt-app-drawer a#logo') } ImprovedTube.improvedtubeYoutubeIcon(); - if (document.documentElement.dataset.pageType === 'video') { - ImprovedTube.expandDescription(); - } + if (document.documentElement.dataset.pageType === 'video') { ImprovedTube.expandDescription(); } if (document.documentElement.dataset.pageType === 'home' && ImprovedTube.storage.youtube_home_page === 'search' ) { document.querySelector('body').style.setProperty('visibility', 'visible', 'important'); ImprovedTube.shortcutGoToSearchBox(); diff --git a/js&css/web-accessible/www.youtube.com/appearance.js b/js&css/web-accessible/www.youtube.com/appearance.js index 681505e4e..cdd4a71fb 100644 --- a/js&css/web-accessible/www.youtube.com/appearance.js +++ b/js&css/web-accessible/www.youtube.com/appearance.js @@ -8,9 +8,7 @@ ImprovedTube.undoTheNewSidebar = function () { yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = false; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments_ep = false; yt.config_.EXPERIMENT_FLAGS.web_watch_rounded_player_large = false; - } catch (error) { - console.error("can't undo description on the side", error); - } + } catch (error) { console.error("can't undo description on the side", error); } } }; @@ -19,9 +17,7 @@ ImprovedTube.descriptionSidebar = function () { yt.config_.EXPERIMENT_FLAGS.kevlar_watch_grid = true; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments = true; yt.config_.EXPERIMENT_FLAGS.small_avatars_for_comments_ep = true; - } catch (error) { - console.error("tried to move description to the sidebar", error); - } + } catch (error) { console.error("tried to move description to the sidebar", error); } }; /*------------------------------------------------------------------------------ PLAYER @@ -41,9 +37,7 @@ ImprovedTube.playerSize = function () { style.textContent += "}"; document.body.appendChild(style); - if (document.documentElement.dataset.pageType === 'video') { - window.dispatchEvent(new Event('resize')); - } + if (document.documentElement.dataset.pageType === 'video') { window.dispatchEvent(new Event('resize')); } } }; /*------------------------------------------------------------------------------ @@ -155,108 +149,104 @@ ImprovedTube.playerRemainingDuration = function () { /*------------------------------------------------------------------------------ Comments Sidebar Simple ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebarSimple = function () { - if (ImprovedTube.storage.comments_sidebar_simple === true) { - if (window.matchMedia("(min-width: 1599px)").matches) { - document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments")); - } - if (window.matchMedia("(max-width: 1598px)").matches) { - document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); - setTimeout(function () { - document.querySelector("#primary-inner").appendChild(document.querySelector("#related")); - } - ); - } - } +ImprovedTube.commentsSidebarSimple = function () { if (ImprovedTube.storage.comments_sidebar_simple === true) { + if (window.matchMedia("(min-width: 1599px)").matches) { + document.querySelector("#primary").insertAdjacentElement('afterend', document.querySelector("#comments"));} + if (window.matchMedia("(max-width: 1598px)").matches) { + document.querySelector("#related").insertAdjacentElement('beforebegin', document.querySelector("#comments")); + setTimeout(function () { + document.querySelector("#primary-inner").appendChild(document.querySelector("#related"));} + );} +} } /*------------------------------------------------------------------------------ Comments Sidebar ------------------------------------------------------------------------------*/ -ImprovedTube.commentsSidebar = function () { - if (ImprovedTube.storage.comments_sidebar === true) { - const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); - let hasApplied = 0; - if (/watch\?/.test(location.href)) { - sidebar(); - styleScrollbars(); - setGrid(); - applyObserver(); - window.addEventListener("resize", sidebar) - } +ImprovedTube.commentsSidebar = function () { if (ImprovedTube.storage.comments_sidebar === true) { + const video = document.querySelector("#player .ytp-chrome-bottom") || document.querySelector("#container .ytp-chrome-bottom"); + let hasApplied = 0; + if (/watch\?/.test(location.href)) { + sidebar(); + styleScrollbars(); + setGrid(); + applyObserver(); + window.addEventListener("resize", sidebar) + } - function sidebar () { - resizePlayer(); - if (window.matchMedia("(min-width: 1952px)").matches) { - - if (!hasApplied) { - initialSetup() - setTimeout(() => { - document.getElementById("columns").appendChild(document.getElementById("related")) - }) - } else if (hasApplied == 2) { //from medium to big size - setTimeout(() => { - document.getElementById("columns").appendChild(document.getElementById("related")) - }) - } - hasApplied = 1 - } else if (window.matchMedia("(min-width: 1000px)").matches) { - if (!hasApplied) { - initialSetup(); - } else if (hasApplied == 1) { //from big to medium - document.getElementById("primary-inner").appendChild(document.getElementById("related")); - } - hasApplied = 2 - } else { /// <1000 - if (hasApplied == 1) { - document.getElementById("primary-inner").appendChild(document.getElementById("related")); - let comments = document.querySelector("#comments"); - let below = document.getElementById("below"); - below.appendChild(comments); - } else if (hasApplied == 2) { - let comments = document.querySelector("#comments"); - let below = document.getElementById("below"); - below.appendChild(comments); - } - hasApplied = 0; + function sidebar () { + resizePlayer(); + if (window.matchMedia("(min-width: 1952px)").matches) { + + if (!hasApplied) { + initialSetup() + setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) } + else if (hasApplied == 2) { //from medium to big size + setTimeout(() => {document.getElementById("columns").appendChild(document.getElementById("related"))}) + } + hasApplied = 1 } - function setGrid () { - let checkParentInterval = setInterval(() => { - container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; - if (container) { - clearInterval(checkParentInterval); - container.style.display = "flex"; - container.style.flexWrap = "wrap"; - container.style.flexDirection = "row"; - } - }, 250); - } - function initialSetup () { - let secondaryInner = document.getElementById("secondary-inner"); - let primaryInner = document.getElementById("primary-inner"); - let comments = document.querySelector("#comments"); - setTimeout(() => { - primaryInner.appendChild(document.getElementById("panels")); - primaryInner.appendChild(document.getElementById("related")) - secondaryInner.appendChild(document.getElementById("chat-template")); - secondaryInner.appendChild(comments); - }) + else if (window.matchMedia("(min-width: 1000px)").matches) { + if (!hasApplied) { + initialSetup(); + } + else if (hasApplied == 1) { //from big to medium + document.getElementById("primary-inner").appendChild(document.getElementById("related")); + } + hasApplied = 2 } - function resizePlayer () { - const width = video.offsetWidth + 24; - const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); - document.getElementById("primary").style.width = `${width}px`; - player.style.width = `${width}px`; + else { /// <1000 + if (hasApplied == 1) { + document.getElementById("primary-inner").appendChild(document.getElementById("related")); + let comments = document.querySelector("#comments"); + let below = document.getElementById("below"); + below.appendChild(comments); + } + else if (hasApplied == 2) { + let comments = document.querySelector("#comments"); + let below = document.getElementById("below"); + below.appendChild(comments); + } + hasApplied = 0; } - function styleScrollbars () { - if (!navigator.userAgent.toLowerCase().includes("mac")) { - let color, colorHover - const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; - if (isDarkMode) [color, colorHover] = ["#616161", "#909090"]; - else [color, colorHover] = ["#aaaaaa", "#717171"]; - const style = document.createElement("style"); - if (ImprovedTube.storage.comments_sidebar_scrollbars === true) { - const cssRule = ` + } + function setGrid () { + let checkParentInterval = setInterval(() => { + container = document.querySelector("#related ytd-compact-video-renderer.style-scope")?.parentElement; + if (container) { + clearInterval(checkParentInterval); + container.style.display = "flex"; + container.style.flexWrap = "wrap"; + container.style.flexDirection = "row"; + } + }, 250); + } + function initialSetup () { + let secondaryInner = document.getElementById("secondary-inner"); + let primaryInner = document.getElementById("primary-inner"); + let comments = document.querySelector("#comments"); + setTimeout(() => { + primaryInner.appendChild(document.getElementById("panels")); + primaryInner.appendChild(document.getElementById("related")) + secondaryInner.appendChild(document.getElementById("chat-template")); + secondaryInner.appendChild(comments); + }) + } + function resizePlayer () { + const width = video.offsetWidth + 24; + const player = document.querySelector("#player.style-scope.ytd-watch-flexy"); + document.getElementById("primary").style.width = `${width}px`; + player.style.width = `${width}px`; + } + function styleScrollbars () { + if (!navigator.userAgent.toLowerCase().includes("mac")) { + let color, colorHover + const isDarkMode = getComputedStyle(document.querySelector('ytd-app')).getPropertyValue('--yt-spec-base-background') == "#0f0f0f"; + if (isDarkMode) [color, colorHover] = ["#616161", "#909090"]; + else [color, colorHover] = ["#aaaaaa", "#717171"]; + const style = document.createElement("style"); + if (ImprovedTube.storage.comments_sidebar_scrollbars === true) { + const cssRule = ` #primary, #secondary { overflow: overlay !important; } @@ -277,9 +267,9 @@ ImprovedTube.commentsSidebar = function () { ::-webkit-scrollbar-thumb:hover{ background-color: ${colorHover}; }`; - style.appendChild(document.createTextNode(cssRule)); - } else { - const cssRule = ` + style.appendChild(document.createTextNode(cssRule)); + } + else { const cssRule = ` #primary, #secondary { overflow: overlay !important; } @@ -288,26 +278,26 @@ ImprovedTube.commentsSidebar = function () { width: 0px; height: 0px; }`; - style.appendChild(document.createTextNode(cssRule)); - } - document.head.appendChild(style); + style.appendChild(document.createTextNode(cssRule)); } + document.head.appendChild(style); } - function applyObserver () { - const debouncedResizePlayer = debounce(resizePlayer, 200); - const resizeObserver = new ResizeObserver(debouncedResizePlayer); - resizeObserver.observe(video); - } - function debounce (callback, delay) { - let timerId; - return function (...args) { - clearTimeout(timerId); - timerId = setTimeout(() => { - callback.apply(this, args); - }, delay); - }; - } } + function applyObserver () { + const debouncedResizePlayer = debounce(resizePlayer, 200); + const resizeObserver = new ResizeObserver(debouncedResizePlayer); + resizeObserver.observe(video); + } + function debounce (callback, delay) { + let timerId; + return function (...args) { + clearTimeout(timerId); + timerId = setTimeout(() => { + callback.apply(this, args); + }, delay); + }; + } +} } /*------------------------------------------------------------------------------ SIDEBAR @@ -315,27 +305,19 @@ ImprovedTube.commentsSidebar = function () { /*---------------------------------------------------------------- TRANSCRIPT --------------------------------------------------------------*/ -ImprovedTube.transcript = function (el) { - if (ImprovedTube.storage.transcript === true) { - el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility'); - } -} +ImprovedTube.transcript = function (el) { if (ImprovedTube.storage.transcript === true) { + el.querySelector('*[target-id*=transcript]')?.removeAttribute('visibility');} } /*---------------------------------------------------------------- CHAPTERS --------------------------------------------------------------*/ -ImprovedTube.chapters = function (el) { - if (ImprovedTube.storage.chapters === true) { - el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility'); - } -} +ImprovedTube.chapters = function (el) { if (ImprovedTube.storage.chapters === true) { + el.querySelector('*[target-id*=chapters]')?.removeAttribute('visibility');} } /*------------------------------------------------------------------------------ LIVECHAT ------------------------------------------------------------------------------*/ ImprovedTube.livechat = function () { if (this.storage.livechat === "collapsed") { - if (typeof isCollapsed === 'undefined') { - var isCollapsed = false; - } + if (typeof isCollapsed === 'undefined') { var isCollapsed = false; } if (ImprovedTube.elements.livechat && !isCollapsed) { ImprovedTube.elements.livechat.button.click(); isCollapsed = true @@ -354,9 +336,7 @@ 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'); @@ -369,9 +349,7 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { var button = document.createElement('button'), svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - var transparentOrOn = .5; if (this.storage.player_always_repeat === true ) { - transparentOrOn = 1; - } + var transparentOrOn = .5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } button.className = 'improvedtube-player-button'; button.id = 'it-below-player-loop'; button.dataset.tooltip = 'Loop'; @@ -445,29 +423,14 @@ ImprovedTube.improvedtubeYoutubeButtonsUnderPlayer = function () { ------------------------------------------------------------------------------*/ ImprovedTube.expandDescription = function (el) { if (this.storage.description === "expanded" || this.storage.description === "classic_expanded") { - if (el) { - el.click(); setTimeout(function () { - ImprovedTube.elements.player.focus(); - }, 1200); - } else { - var tries = 0; var intervalMs = 210; - if (location.href.indexOf('/watch?') !== -1) { - var maxTries = 10; - } else { - var maxTries = 0; - } + if (el) {el.click(); setTimeout(function () {ImprovedTube.elements.player.focus();}, 1200); } + else { var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} // ...except when it is an embedded player? var waitForDescription = setInterval(() => { if (++tries >= maxTries) { el = document.querySelector('#description-inline-expander') - if ( el) { - el.click(); setTimeout(function () { - ImprovedTube.elements.player.focus(); - }, 1200); clearInterval(waitForDescription); - } - intervalMs *= 1.11; - } - }, intervalMs); + if ( el) { el.click(); setTimeout(function () {ImprovedTube.elements.player.focus(); }, 1200); clearInterval(waitForDescription); } + intervalMs *= 1.11; }}, intervalMs); } } } @@ -491,16 +454,10 @@ ImprovedTube.expandDescription = function (el) { ImprovedTube.dayOfWeek = function () { if (this.storage.day_of_week === true) { var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; - setTimeout(function () { - var videoDate; - try { - videoDate = JSON.parse(document.querySelector('#microformat script')?.textContent)?.uploadDate - } catch { - //YouTube related video or internal link? - try { - videoDate = document.querySelector("[itemprop=datePublished]").content; - } catch { } - } //..no? must be new session? + 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 tempDate = new Date(videoDate); var element = document.querySelector(".ytd-day-of-week"); if (!element) { @@ -508,11 +465,8 @@ 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); + 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] + ", "; } diff --git a/js&css/web-accessible/www.youtube.com/channel.js b/js&css/web-accessible/www.youtube.com/channel.js index a595ae94c..f341886eb 100644 --- a/js&css/web-accessible/www.youtube.com/channel.js +++ b/js&css/web-accessible/www.youtube.com/channel.js @@ -59,12 +59,10 @@ ImprovedTube.channelCompactTheme = function () { compact.hasApplied = true initialLoad(); document.querySelector("#sections #items") ? styleWithListeners() : styleWithInterval(); - } else if (compact.hasApplied) { //cleanup - try { - clearInterval(compact.listener) - } catch (err) { - console.log("ERR: We couldn't clear listener. Reload page") - } + } + else if (compact.hasApplied) { //cleanup + try {clearInterval(compact.listener)} + catch (err) {console.log("ERR: We couldn't clear listener. Reload page")} if (compact.eventHandlerFns.length) removeListeners(); if (compact.styles.length) removeStyles() compact = {} @@ -94,7 +92,8 @@ ImprovedTube.channelCompactTheme = function () { if (!isCompact) { sub.style.display = "none" isCompact = true - } else { + } + else { sub.style.display = "" isCompact = false } diff --git a/js&css/web-accessible/www.youtube.com/player.js b/js&css/web-accessible/www.youtube.com/player.js index 3d3c58845..3b2222d0e 100644 --- a/js&css/web-accessible/www.youtube.com/player.js +++ b/js&css/web-accessible/www.youtube.com/player.js @@ -7,19 +7,16 @@ 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 (there is a player) and (no user clicks) and (no ads playing) - // and ( ( it is not in a playlist and auto play is off ) - // or ( playlist auto play is off and in a playlist ) - // or ( we are in a channel and the channel trailer autoplay is off ) ) - - // user didnt click - if (player && !this.user_interacted - // no ads playing - && !player.classList.contains('ad-showing') - // video page - && ((location.href.includes('/watch?') // #1703 + 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) + // or (playlist auto play is off and in a playlist)) + // or (we are in a channel and the channel trailer autoplay is off) ) + + if (player && !this.user_interacted // (=user didnt click or type) + & !player.classList.contains('ad-showing') // (=no ads playing, needs an update?) + && ((location.href.includes('/watch?') // #1703 // (=video page) // player_autoplay_disable & not playlist && (this.storage.player_autoplay_disable && !location.href.includes('list=')) // !playlist_autoplay & playlist @@ -28,11 +25,7 @@ ImprovedTube.autoplayDisable = function (videoElement) { || (this.storage.channel_trailer_autoplay === false && this.regex.channel.test(location.href)))) { setTimeout(function () { - try { - player.pauseVideo(); - } catch (error) { - console.log("autoplayDisable: Pausing"); videoElement.pause(); - } + try { player.pauseVideo(); } catch (error) { console.log("autoplayDisable: Pausing"); videoElement.pause(); } }); } else { document.dispatchEvent(new CustomEvent('it-play')); @@ -52,9 +45,7 @@ ImprovedTube.forcedPlayVideoFromTheBeginning = function () { if (player && video && this.storage.forced_play_video_from_the_beginning && location.pathname == '/watch') { player.seekTo(0); // restore previous paused state - if (paused) { - player.pauseVideo(); - } + if (paused) { player.pauseVideo(); } } }; /*------------------------------------------------------------------------------ @@ -138,76 +129,53 @@ ImprovedTube.playbackSpeed = function (newSpeed) { /*------------------------------------------------------------------------------ FORCED PLAYBACK SPEED ------------------------------------------------------------------------------*/ -ImprovedTube.playerPlaybackSpeed = function () { - if (this.storage.player_forced_playback_speed === true) { - var player = this.elements.player, - video = player.querySelector('video'), - option = this.storage.player_playback_speed; - if (this.isset(option) === false) { - option = 1; - } else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) ) { - console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; - } - if ( !player.getVideoData().isLive || player.getVideoData().isLive === false) { - player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl - if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true) +ImprovedTube.playerPlaybackSpeed = function () { if (this.storage.player_forced_playback_speed === true) { + var player = this.elements.player, + video = player.querySelector('video'), + option = this.storage.player_playback_speed; + if (this.isset(option) === false) { option = 1; } + else if ( option !== 1 && video.playbackRate !== option && (video.playbackRate > 1 || video.playbackRate < 1) ) + { console.log("skipping permanent speed, since speed was manually set differently for this video to:" + video.playbackRate); return; } + if ( !player.getVideoData().isLive || player.getVideoData().isLive === false) + { player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); // #1729 q2 // hi! @raszpl + if ( (this.storage.player_force_speed_on_music !== true || this.storage.player_dont_speed_education === true) && option !== 1) { - ImprovedTube.speedException = function () { - if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education') { - player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return; - } - if (this.storage.player_force_speed_on_music === true) { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); - return; - } - if (DATA.keywords && !keywords) { - keywords = DATA.keywords.join(', ') || ''; - } - if (keywords === 'video, sharing, camera phone, video phone, free, upload') { - keywords = ''; - } - var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i; - var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i; - var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i"); - var musicRegexMatch = musicIdentifiersTitle.test(DATA.title); - if (!musicRegexMatch) { - var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i; - var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i"); + ImprovedTube.speedException = function () { + if (this.storage.player_dont_speed_education === true && DATA.genre === 'Education') + {player.setPlaybackRate(Number(1)); video.playbackRate = Number(1); return;} + if (this.storage.player_force_speed_on_music === true) + { //player.setPlaybackRate(Number(option)); video.playbackRate = Number(option); + return;} + if (DATA.keywords && !keywords) { keywords = DATA.keywords.join(', ') || ''; } + if (keywords === 'video, sharing, camera phone, video phone, free, upload') { keywords = ''; } + var musicIdentifiers = /(official|music|lyrics?)[ -]video|(cover|studio|radio|album|alternate)[- ]version|soundtrack|unplugged|\bmedley\b|\blo-fi\b|\blofi\b|a(lla)? cappella|feat\.|(piano|guitar|jazz|ukulele|violin|reggae)[- ](version|cover)|karaok|backing[- ]track|instrumental|(sing|play)[- ]?along|卡拉OK|卡拉OK|الكاريوكي|караоке|カラオケ|노래방|bootleg|mashup|Radio edit|Guest (vocals|musician)|(title|opening|closing|bonus|hidden)[ -]track|live acoustic|interlude|featuring|recorded (at|live)/i; + var musicIdentifiersTitleOnly = /lyrics|theme song|\bremix|\bAMV ?[^a-z0-9]|[^a-z0-9] ?AMV\b|\bfull song\b|\bsong:|\bsong[\!$]|^song\b|( - .*\bSong\b|\bSong\b.* - )|cover ?[^a-z0-9]|[^a-z0-9] ?cover|\bconcert\b/i; + var musicIdentifiersTitle = new RegExp(musicIdentifiersTitleOnly.source + '|' + musicIdentifiers.source, "i"); + var musicRegexMatch = musicIdentifiersTitle.test(DATA.title); + if (!musicRegexMatch) { + var musicIdentifiersTagsOnly = /, (lyrics|remix|song|music|AMV|theme song|full song),|\(Musical Genre\)|, jazz|, reggae/i; + var musicIdentifiersTags = new RegExp(musicIdentifiersTagsOnly.source + '|' + musicIdentifiers.source, "i"); keywordsAmount = 1 + ((keywords || '').match(/,/) || []).length; - if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) { - musicRegexMatch = true - } - } - notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); - // (Tags/keywords shouldnt lie & very few songs titles might have these words) - if (DATA.duration) { - function parseDuration (duration) { - const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); - return h * 3600 + m * 60 + s; - } - DATA.lengthSeconds = parseDuration(DATA.duration); - } - function testSongDuration (s, ytMusic) { - if (135 <= s && s <= 260) { - return 'veryCommon'; - } - if (105 <= s && s <= 420) { - return 'common'; - } - if (420 <= s && s <= 720) { - return 'long'; - } - if (45 <= s && s <= 105) { - return 'short'; - } - if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) { - return 'multiple'; - } - //does Youtube ever show more than 10 songs below the description? - } - var songDurationType = testSongDuration(DATA.lengthSeconds); - console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType); - // check if the video is PROBABLY MUSIC: - if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon')) + if ( ((keywords || '').match(musicIdentifiersTags) || []).length / keywordsAmount > 0.08) { + musicRegexMatch = true}} + notMusicRegexMatch = /\bdo[ck]u|interv[iyj]|back[- ]?stage|インタビュー|entrevista|面试|面試|회견|wawancara|مقابلة|интервью|entretien|기록한 것|记录|記錄|ドキュメンタリ|وثائقي|документальный/i.test(DATA.title + " " + keywords); + // (Tags/keywords shouldnt lie & very few songs titles might have these words) + if (DATA.duration) { + function parseDuration (duration) { const [_, h = 0, m = 0, s = 0] = duration.match(/PT(?:(\d+)?H)?(?:(\d+)?M)?(\d+)?S?/).map(part => parseInt(part) || 0); + return h * 3600 + m * 60 + s; } + DATA.lengthSeconds = parseDuration(DATA.duration); } + function testSongDuration (s, ytMusic) { + if (135 <= s && s <= 260) {return 'veryCommon';} + if (105 <= s && s <= 420) {return 'common';} + if (420 <= s && s <= 720) {return 'long';} + if (45 <= s && s <= 105) {return 'short';} + if (ytMusic && ytMusic > 1 && (85 <= s / ytMusic && (s / ytMusic <= 375 || ytMusic == 10))) {return 'multiple';} + //does Youtube ever show more than 10 songs below the description? + } + var songDurationType = testSongDuration(DATA.lengthSeconds); + console.log("genre: " + DATA.genre + "//title: " + DATA.title + "//keywords: " + keywords + "//music word match: " + musicRegexMatch + "// not music word match:" + notMusicRegexMatch + "//duration: " + DATA.lengthSeconds + "//song duration type: " + songDurationType); + // check if the video is PROBABLY MUSIC: + if ( ( DATA.genre === 'Music' && (!notMusicRegexMatch || songDurationType === 'veryCommon')) || ( musicRegexMatch && !notMusicRegexMatch && (typeof songDurationType !== 'undefined' || (/album|Álbum|专辑|專輯|एलबम|البوم|アルバム|альбом|앨범|mixtape|concert|playlist|\b(live|cd|vinyl|lp|ep|compilation|collection|symphony|suite|medley)\b/i.test(DATA.title + " " + keywords) && 1000 <= DATA.lengthSeconds )) ) // && 1150 <= DATA.lengthSeconds <= 5000 @@ -216,123 +184,74 @@ ImprovedTube.playerPlaybackSpeed = function () { && 1000 <= DATA.lengthSeconds )) ) // && DATA.lengthSeconds <= 5000 || (amountOfSongs && testSongDuration(DATA.lengthSeconds, amountOfSongs ) !== 'undefined') // || location.href.indexOf('music.') !== -1 // (=currently we are only running on www.youtube.com anyways) - ) { - player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); - } else { // Now this video might rarely be music + ) { player.setPlaybackRate(1); video.playbackRate = 1; console.log ("...,thus must be music?"); } + else { // Now this video might rarely be music // - however we can make extra-sure after waiting for the video descripion to load... (#1539) - var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) { - var maxTries = 10; - } else { - var maxTries = 0; - } - // ...except when it is an embedded player? - var waitForDescription = setInterval(() => { - if (++tries >= maxTries) { - subtitle = document.querySelector('#title + #subtitle:last-of-type') - if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs) + var tries = 0; var intervalMs = 210; if (location.href.indexOf('/watch?') !== -1) {var maxTries = 10;} else {var maxTries = 0;} + // ...except when it is an embedded player? + var waitForDescription = setInterval(() => { + if (++tries >= maxTries) { + subtitle = document.querySelector('#title + #subtitle:last-of-type') + if ( subtitle && 1 <= Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) // indicates buyable/registered music (amount of songs) && typeof testSongDuration(DATA.lengthSeconds, Number((subtitle?.innerHTML?.match(/^\d+/) || [])[0]) ) !== 'undefined' ) // resonable duration - { - player.setPlaybackRate(1); video.playbackRate = 1; console.log("...but YouTube shows music below the description!"); clearInterval(waitForDescription); - } - intervalMs *= 1.11; - } - }, intervalMs); - window.addEventListener('load', () => { - setTimeout(() => { - clearInterval(waitForDescription); - }, 1234); - }); - } + {player.setPlaybackRate(1); video.playbackRate = 1; console.log("...but YouTube shows music below the description!"); clearInterval(waitForDescription); } + intervalMs *= 1.11; }}, intervalMs); + window.addEventListener('load', () => { setTimeout(() => { clearInterval(waitForDescription); }, 1234); }); } - //DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere) - DATA = {}; - defaultKeywords = "video,sharing,camera,phone,video phone,free,upload"; - DATA.keywords = false; keywords = false; amountOfSongs = false; - DATA.videoID = ImprovedTube.videoId() || false; - ImprovedTube.fetchDOMData = function () { - // if (history.length > 1 && history.state.endpoint.watchEndpoint) { + } + //DATA (TO-DO: make the Data available to more/all features? #1452 #1763 (Then can replace ImprovedTube.elements.category === 'music', VideoID is also used elsewhere) + DATA = {}; + defaultKeywords = "video,sharing,camera,phone,video phone,free,upload"; + DATA.keywords = false; keywords = false; amountOfSongs = false; + DATA.videoID = ImprovedTube.videoId() || false; + ImprovedTube.fetchDOMData = function () { + // if (history.length > 1 && history.state.endpoint.watchEndpoint) { + try { DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name;} + catch { DATA.genre = false; DATA.keywords = false; DATA.lengthSeconds = false; try { - DATA = JSON.parse(document.querySelector('#microformat script')?.textContent) ?? false; DATA.title = DATA.name; - } catch { - DATA.genre = false; DATA.keywords = false; DATA.lengthSeconds = false; - try { - DATA.title = document.getElementsByTagName('meta')?.title?.content || false; - DATA.genre = document.querySelector('meta[itemprop=genre]')?.content || false; - DATA.duration = document.querySelector('meta[itemprop=duration]')?.content || false; - } catch {} - } if ( DATA.title === ImprovedTube.videoTitle() ) { - keywords = document.getElementsByTagName('meta')?.keywords?.content || false; if (!keywords) { - keyword='' - } ImprovedTube.speedException(); - } else { - keywords = ''; (async function () { - try { - const response = await fetch(`https://www.youtube.com/watch?v=${DATA.videoID}`); - - const htmlContent = await response.text(); - const metaRegex = /]+name=["'](keywords|genre|duration)["'][^>]+content=["']([^"']+)["'][^>]*>/gi; - let match; while ((match = metaRegex.exec(htmlContent)) !== null) { - const [, property, value] = match; - if (property === 'keywords') { - keywords = value; - } else { - DATA[property] = value; - } - } - amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false; - if (keywords) { - ImprovedTube.speedException(); - } - } catch (error) { - console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; - } - })(); + 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;} } - }; - if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { - ImprovedTube.fetchDOMData(); - } else { + amountOfSongs = (htmlContent.slice(-80000).match(/},"subtitle":{"simpleText":"(\d*)\s/) || [])[1] || false; + if (keywords) { ImprovedTube.speedException(); } + } catch (error) { console.error('Error: fetching from https://Youtube.com/watch?v=${DATA.videoID}', error); keywords = ''; } + })(); + } + }; + if ( (history && history.length === 1) || !history?.state?.endpoint?.watchEndpoint) { ImprovedTube.fetchDOMData();} + else { //Invidious instances. Should be updated automatically!... - const invidiousInstances = ['invidious.fdn.fr', 'inv.tux.pizza', 'invidious.flokinet.to', 'invidious.protokolla.fi', 'invidious.private.coffee', 'yt.artemislena.eu', 'invidious.perennialte.ch', 'invidious.materialio.us', 'iv.datura.network']; - function getRandomInvidiousInstance () { - return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)]; - } + const invidiousInstances = ['invidious.fdn.fr', 'inv.tux.pizza', 'invidious.flokinet.to', 'invidious.protokolla.fi', 'invidious.private.coffee', 'yt.artemislena.eu', 'invidious.perennialte.ch', 'invidious.materialio.us', 'iv.datura.network']; + function getRandomInvidiousInstance () { return invidiousInstances[Math.floor(Math.random() * invidiousInstances.length)];} - (async function () { - let retries = 4; let invidiousFetched = false; - async function fetchInvidiousData () { - try { - const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); + (async function () { let retries = 4; let invidiousFetched = false; + async function fetchInvidiousData () { + try {const response = await fetch(`https://${getRandomInvidiousInstance()}/api/v1/videos/${DATA.videoID}?fields=genre,title,lengthSeconds,keywords`); DATA = await response.json(); - if (DATA.genre && DATA.title && DATA.keywords && DATA.lengthSeconds) { - if (DATA.keywords.toString() === defaultKeywords ) { - DATA.keywords = '' - } - ImprovedTube.speedException(); invidiousFetched = true; - } - } catch (error) { - console.error('Error: Invidious API: ', error); - } - } - while (retries > 0 && !invidiousFetched) { - await fetchInvidiousData(); - if (!invidiousFetched) { - await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; - } - } - if (!invidiousFetched) { - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData()) - } else { - ImprovedTube.fetchDOMData(); - } - } - })(); - } - } // else { } - } + if (DATA.genre && DATA.title && DATA.keywords && DATA.lengthSeconds) { if (DATA.keywords.toString() === defaultKeywords ) {DATA.keywords = ''} + ImprovedTube.speedException(); invidiousFetched = true; } + } catch (error) { console.error('Error: Invidious API: ', error); } + } + while (retries > 0 && !invidiousFetched) { await fetchInvidiousData(); + if (!invidiousFetched) { await new Promise(resolve => setTimeout(resolve, retries === 4 ? 1500 : 876)); retries--; } } + if (!invidiousFetched) { if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', ImprovedTube.fetchDOMData())} + else { ImprovedTube.fetchDOMData();} } + })(); + } + } // else { } } } +} /*------------------------------------------------------------------------------ SUBTITLES ------------------------------------------------------------------------------*/ @@ -347,9 +266,7 @@ ImprovedTube.playerSubtitles = function () { break case 'disabled': - if (player.isSubtitlesOn()) { - player.toggleSubtitles(); - } + if (player.isSubtitlesOn()) { player.toggleSubtitles(); } break } } @@ -369,9 +286,7 @@ ImprovedTube.subtitlesLanguage = function () { subtitlesState = player.isSubtitlesOn(); player.setOption('captions', 'track', matchedTrack); // setOption forces Subtitles ON, restore state from before calling it. - if (!subtitlesState) { - player.toggleSubtitles(); - } + if (!subtitlesState) { player.toggleSubtitles(); } } } }; @@ -651,9 +566,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; } } @@ -711,9 +624,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); } @@ -726,9 +637,7 @@ ImprovedTube.screenshot = function () { 'image/png': blob }) ]) - .then(function () { - console.log("ImprovedTube: Screeeeeeenshot tada!"); - }) + .then(function () { console.log("ImprovedTube: Screeeeeeenshot tada!"); }) .catch(function (error) { console.log('ImprovedTube screenshot: ', error); alert('ImprovedTube Screenshot to Clipboard error. Details in Debug Console.'); @@ -809,9 +718,7 @@ ImprovedTube.playerRepeatButton = function () { svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); path.setAttributeNS(null, 'd', 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z'); svg.appendChild(path); - var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { - transparentOrOn = 1; - } + var transparentOrOn = 0.5; if (this.storage.player_always_repeat === true ) { transparentOrOn = 1; } this.createPlayerButton({ id: 'it-repeat-button', child: svg, @@ -970,7 +877,8 @@ ImprovedTube.playerCinemaModeButton = function () { player.style.zIndex = 1; svg.parentNode.style.opacity = 0.64; svg.parentNode.style.zIndex = 1; - } else { + } + else { player.style.zIndex = 10000; svg.parentNode.style.opacity = 1; } @@ -1028,56 +936,55 @@ ImprovedTube.playerCinemaModeEnable = function () { /*------------------------------------------------------------------------------ HAMBURGER MENU ------------------------------------------------------------------------------*/ -ImprovedTube.playerHamburgerButton = function () { - if (this.storage.player_hamburger_button === true) { - const videoPlayer = document.querySelector('.html5-video-player'); +ImprovedTube.playerHamburgerButton = function () { if (this.storage.player_hamburger_button === true) { + const videoPlayer = document.querySelector('.html5-video-player'); - if (!videoPlayer) { - return; - } + if (!videoPlayer) { + return; + } - const controlsContainer = videoPlayer.querySelector('.ytp-right-controls'); + const controlsContainer = videoPlayer.querySelector('.ytp-right-controls'); - if (!controlsContainer) { - return; - } + if (!controlsContainer) { + return; + } - let hamburgerMenu = document.querySelector('.custom-hamburger-menu'); - if (!hamburgerMenu) { - hamburgerMenu = document.createElement('div'); - hamburgerMenu.className = 'custom-hamburger-menu'; - hamburgerMenu.style.position = 'absolute'; - hamburgerMenu.style.right = '0'; - hamburgerMenu.style.marginTop = '8px'; - hamburgerMenu.style.cursor = 'pointer'; + let hamburgerMenu = document.querySelector('.custom-hamburger-menu'); + if (!hamburgerMenu) { + hamburgerMenu = document.createElement('div'); + hamburgerMenu.className = 'custom-hamburger-menu'; + hamburgerMenu.style.position = 'absolute'; + hamburgerMenu.style.right = '0'; + hamburgerMenu.style.marginTop = '8px'; + hamburgerMenu.style.cursor = 'pointer'; + + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); + svg.setAttribute('style', 'width: 32px; height: 32px;'); - const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - svg.setAttributeNS(null, 'viewBox', '0 0 24 24'); - svg.setAttribute('style', 'width: 32px; height: 32px;'); + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z'); + path.setAttributeNS(null, 'fill', 'white'); - const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - path.setAttributeNS(null, 'd', 'M3 18h18v-2H3v2zM3 13h18v-2H3v2zM3 6v2h18V6H3z'); - path.setAttributeNS(null, 'fill', 'white'); + svg.appendChild(path); + hamburgerMenu.appendChild(svg); - svg.appendChild(path); - hamburgerMenu.appendChild(svg); + controlsContainer.style.paddingRight = '40px'; + controlsContainer.parentNode.appendChild(hamburgerMenu); - controlsContainer.style.paddingRight = '40px'; - controlsContainer.parentNode.appendChild(hamburgerMenu); + let controlsVisible = true; + controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; + controlsVisible = false; - let controlsVisible = true; + hamburgerMenu.addEventListener('click', function () { controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; - controlsVisible = false; - - hamburgerMenu.addEventListener('click', function () { - controlsContainer.style.display = controlsVisible ? 'none' : 'flex'; - controlsVisible = !controlsVisible; + controlsVisible = !controlsVisible; - // Change the opacity of hamburgerMenu based on controls visibility - hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65'; - }); - } + // Change the opacity of hamburgerMenu based on controls visibility + hamburgerMenu.style.opacity = controlsVisible ? '0.85' : '0.65'; + }); } +} }; /*------------------------------------------------------------------------------ POPUP PLAYER @@ -1530,62 +1437,61 @@ ImprovedTube.miniPlayer = function () { /*------------------------------------------------------------------------------ CUSTOM PAUSE FUNCTIONS ------------------------------------------------------------------------------*/ -ImprovedTube.pauseWhileTypingOnYoutube = function () { - if (ImprovedTube.storage.pause_while_typing_on_youtube === true) { - var timeoutId; // Declare a variable to hold the timeout ID +ImprovedTube.pauseWhileTypingOnYoutube = function () { if (ImprovedTube.storage.pause_while_typing_on_youtube === true) { + var timeoutId; // Declare a variable to hold the timeout ID - // Add event listener to the whole document - document.addEventListener('keydown', function (e) { + // Add event listener to the whole document + document.addEventListener('keydown', function (e) { // Check on the storage for pause_while_typing_on_youtube_storage is false - // If player is NOT in the viewport, return - if (!isPlayerInViewport()) { - return; - } + // If player is NOT in the viewport, return + if (!isPlayerInViewport()) { + return; + } - var player = ImprovedTube.elements.player; + var player = ImprovedTube.elements.player; - if (player) { - if ( - (/^[a-z0-9]$/i.test(e.key) || e.key === "Backspace") && + if (player) { + if ( + (/^[a-z0-9]$/i.test(e.key) || e.key === "Backspace") && !(e.ctrlKey && (e.key === "c" || e.key === "x" || e.key === "a")) && - ( document.activeElement.tagName === "INPUT" || document.activeElement.tagName === "TEXTAREA" || document.activeElement.tagName === "DIV" )) { + ( document.activeElement.tagName === "INPUT" || document.activeElement.tagName === "TEXTAREA" || document.activeElement.tagName === "DIV" )) + { // Pause the video // Check if player is paused - if (!player.paused) { - player.pauseVideo(); - } - - // Clear any existing timeout - if (timeoutId) { - clearTimeout(timeoutId); - } + if (!player.paused) { + player.pauseVideo(); + } - // Set a new timeout to play the video after 1 second - timeoutId = setTimeout(function () { - player.playVideo(); - }, 2000); // 2000 milliseconds = 2 seconds + // Clear any existing timeout + if (timeoutId) { + clearTimeout(timeoutId); } + + // Set a new timeout to play the video after 1 second + timeoutId = setTimeout(function () { + player.playVideo(); + }, 2000); // 2000 milliseconds = 2 seconds } - }); + } + }); - function isPlayerInViewport () { - var player = ImprovedTube.elements.player; - if (player) { - var rect = player.getBoundingClientRect(); - var windowHeight = (window.innerHeight || document.documentElement.clientHeight); - var windowWidth = (window.innerWidth || document.documentElement.clientWidth); + function isPlayerInViewport () { + var player = ImprovedTube.elements.player; + if (player) { + var rect = player.getBoundingClientRect(); + var windowHeight = (window.innerHeight || document.documentElement.clientHeight); + var windowWidth = (window.innerWidth || document.documentElement.clientWidth); - // Check if the player is in the viewport - return ( - rect.top != 0 && + // Check if the player is in the viewport + return ( + rect.top != 0 && rect.left != 0 && rect.bottom <= windowHeight && rect.right <= windowWidth - ); - } - return false; + ); } - + return false; } -}; + +}}; diff --git a/js&css/web-accessible/www.youtube.com/playlist.js b/js&css/web-accessible/www.youtube.com/playlist.js index 3b3aa91f1..291b595fd 100644 --- a/js&css/web-accessible/www.youtube.com/playlist.js +++ b/js&css/web-accessible/www.youtube.com/playlist.js @@ -4,16 +4,15 @@ /*------------------------------------------------------------------------------ 4.5.1 UP NEXT AUTOPLAY ------------------------------------------------------------------------------*/ -ImprovedTube.playlistUpNextAutoplay = function () { - if (this.storage.playlist_up_next_autoplay === false) { - const playlistData = this.elements.ytd_watch?.playlistData; - if (this.getParam(location.href, 'list') && playlistData +ImprovedTube.playlistUpNextAutoplay = function () { if (this.storage.playlist_up_next_autoplay === false) { + const playlistData = this.elements.ytd_watch?.playlistData; + if (this.getParam(location.href, 'list') && playlistData && playlistData.currentIndex && playlistData.totalVideos && playlistData.localCurrentIndex) { - playlistData.currentIndex = playlistData.totalVideos; - } + playlistData.currentIndex = playlistData.totalVideos; } +} }; /*------------------------------------------------------------------------------ 4.5.2 REVERSE @@ -103,9 +102,8 @@ ImprovedTube.playlistRepeat = function () { && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Loop video' && button.querySelector("#tooltip")?.textContent !== 'Turn off loop' && button.firstElementChild?.firstElementChild?.attributes[2]?.textContent !== 'Turn off loop' - ) { - button.click(); - } + ) + { button.click(); } }, 10000); } }; @@ -122,9 +120,8 @@ ImprovedTube.playlistShuffle = function () { option = ImprovedTube.storage.playlist_shuffle; button = document.querySelector('#playlist-actions #playlist-action-menu ytd-toggle-button-renderer'); if (button && (option === true && button.querySelector("path").attributes.d.textContent.split(" ")[0].startsWith('M18.1') - ) ) { - button.click(); - } + ) ) + { button.click(); } }, 10000); } }; @@ -190,18 +187,9 @@ ImprovedTube.playlistPopupCreateButton = function (playlistID, altButtonStyle, c let height = ImprovedTube.elements.player.offsetHeight * 0.7 ?? innerHeight * 0.45; if (!ImprovedTube.elements.player) { shorts = /short/.test(this.parentElement.href); - if ( width / height < 1 ) { - vertical = true - } else { - vertical = false - } - if ( !vertical && shorts ) { - width = height * 0.6 - } - if ( vertical && !shorts ) { - height = width * 0.6 - } - } + if ( width / height < 1 ) { vertical = true } else { vertical = false } + if ( !vertical && shorts ) { width = height * 0.6} + if ( vertical && !shorts ) { height = width * 0.6} } "use strict"; window.open(`${location.protocol}//www.youtube.com/embed/videoseries?autoplay=${ImprovedTube.storage.player_autoplay_disable ? '0' : '1'}&list=${this.dataset.list}`, '_blank', `directories=no,toolbar=no,location=no,menubar=no,status=no,titlebar=no,scrollbars=no,resizable=no,width=${width / 3},height=${height / 3}`); //~ change focused tab to URL-less popup @@ -258,8 +246,5 @@ ImprovedTube.playlistPopupUpdate = function () { if (panelItemButtons == null) this.elements.buttons['it-popup-playlist-button-panel'] = null; else panelItemButtons.appendChild(this.elements.buttons['it-popup-playlist-button-panel'] = this.playlistPopupCreateButton(playlistID, true, true)); } else if (playlistID != null && this.elements.buttons['it-popup-playlist-button-panel'].dataset.list !== playlistID) this.elements.buttons['it-popup-playlist-button-panel'].dataset.list = playlistID; - } catch (error) { - console.error("Error appending playlist button panel:", error); - } - } -}; + } catch (error) { console.error("Error appending playlist button panel:", error);} + }}; diff --git a/js&css/web-accessible/www.youtube.com/settings.js b/js&css/web-accessible/www.youtube.com/settings.js index 407405adc..20bd387dd 100644 --- a/js&css/web-accessible/www.youtube.com/settings.js +++ b/js&css/web-accessible/www.youtube.com/settings.js @@ -113,7 +113,8 @@ ImprovedTube.improvedtubeYoutubeIcon = function () { if (option === 'header_left') { if (this.storage.header_position === 'normal' && this.elements.masthead.start) { this.elements.masthead.start.appendChild(button); - } else if (this.elements.app_drawer.start) { + } + else if (this.elements.app_drawer.start) { this.elements.app_drawer.start.appendChild(button); } } else if (option === 'header_right') { @@ -159,9 +160,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 87cea62b2..f16c9af21 100644 --- a/js&css/web-accessible/www.youtube.com/shortcuts.js +++ b/js&css/web-accessible/www.youtube.com/shortcuts.js @@ -416,33 +416,15 @@ ImprovedTube.shortcutActivateCaptions = function () { }; /*------Chapters------*/ ImprovedTube.shortcutChapters = function () { - try { - var height = document.querySelector('*[target-id*=chapters]').clientHeight; - } catch {} - if (height) { - try { - document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close") - } catch {} - } else { - try { - document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open") - } catch {} - } + try {var height = document.querySelector('*[target-id*=chapters]').clientHeight;} catch {} + if (height) {try {document.querySelector('*[target-id*=chapters] #visibility-button button').click(); console.log("chapters shortcut close")} catch {}} + else { try {document.querySelector('*[target-id*=chapters]').removeAttribute('visibility'); console.log("chapters shortcut open")} catch {} } }; /*------Transcript------*/ ImprovedTube.shortcutTranscript = function () { - try { - var height = document.querySelector('*[target-id*=transcript]').clientHeight; - } catch {} - if (height) { - try { - document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close") - } catch {} - } else { - try { - document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open") - } catch {} - } + try {var height = document.querySelector('*[target-id*=transcript]').clientHeight;} catch {} + if (height) {try {document.querySelector('*[target-id*=transcript] #visibility-button button').click(); console.log("transcriptshortcut close")} catch {}} + else { try {document.querySelector('*[target-id*=transcript]').removeAttribute('visibility'); console.log("transcriptshortcut open")} catch {} } }; /*------------------------------------------------------------------------------ 4.7.22 LIKE @@ -458,47 +440,19 @@ ImprovedTube.shortcutDislike = function () { }; /*------Report------*/ ImprovedTube.shortcutReport = function () { - try { - document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); - document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0) - } catch { - console.log("'...' failed"); setTimeout(function () { - try { - document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0) - } catch { - console.log("'...' failed2") - } - }, 100) + try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); + document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} + catch {console.log("'...' failed"); setTimeout(function () {try {document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0)} + catch {console.log("'...' failed2")}}, 100) } + + setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} + catch {console.log("report failed"); setTimeout(function () {try {document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click();} + catch {console.log("report failed2"); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click();}}, 800); } - - setTimeout(function () { - try { - document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 0); document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click(); - } catch { - console.log("report failed"); setTimeout(function () { - try { - document.querySelector('tp-yt-iron-dropdown svg path[d^="M13.18,4l0.24,1.2L13.58,6h0.82H19v7h-5.18l-0"]').closest("tp-yt-paper-item").click(); - } catch { - console.log("report failed2"); document.querySelector('svg path[d^="M7.5,12c0,0.83-0.67,1.5-1.5"]').closest("button").click(); - } - }, 800); - } }, 200); - setTimeout(function () { - try { - document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1) - } catch { - console.log("dropdown visible failed"); - setTimeout(function () { - try { - document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1) - } catch { - console.log("dropdown visible failed2"); - } - }, 1700) - } - }, 700) + setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed"); + setTimeout(function () {try {document.querySelectorAll("tp-yt-iron-dropdown").forEach(el => el.style.opacity = 1)} catch {console.log("dropdown visible failed2");}}, 1700)}}, 700) } /*------------------------------------------------------------------------------ 4.7.24 SUBSCRIBE diff --git a/menu/index.js b/menu/index.js index b7630ac7e..00617bcfb 100644 --- a/menu/index.js +++ b/menu/index.js @@ -7,9 +7,7 @@ --------------------------------------------------------------*/ satus.storage.import(function (items) { var language = items.language; - if (!language || language === 'default') { - language = false; - } + if (!language || language === 'default') { language = false;} satus.locale.import(language, function () { satus.render(extension.skeleton); diff --git a/menu/satus.js b/menu/satus.js index 19263d9bb..556c651db 100644 --- a/menu/satus.js +++ b/menu/satus.js @@ -252,9 +252,11 @@ satus.isNumber = function (t) { return (typeof t ==='number' && !isNaN(t)); }; satus.isObject = function (t) { return (t instanceof Object && t !== null); }; satus.isElement = function (t) { return (t instanceof Element || t instanceof HTMLDocument); }; satus.isNodeList = function (t) { return t instanceof NodeList; }; -satus.isBoolean = function (t) { return (t === false || t === true); }; +satus.isBoolean = function (t) { return (t === false || t === true); }; + /*---LOG------------------------------------------------------*/ -satus.log = function () { console.log.apply(null, arguments);}; +satus.log = function () { console.log.apply(null, arguments);}; + /*-------------------------------------------------------------- # DOM @@ -1048,29 +1050,27 @@ satus.locale.import = function (code, callback, path) { importLocale(language, () => importLocale('en', callback)); } } else { // try chrome://settings/languages: - try { - chrome.i18n.getAcceptLanguages(function (languages) { - languages = languages.map(language => language.replace('-', '_')); - for (let i = languages.length - 1; i >= 0; i--) { - if (languages[i].includes('_')) { - let languageWithoutCountryCode = languages[i].substring(0, 2); - - if (!languages.includes(languageWithoutCountryCode)) { - languages.splice(i + 1, 0, languageWithoutCountryCode); - } + try {chrome.i18n.getAcceptLanguages(function (languages) { + languages = languages.map(language => language.replace('-', '_')); + for (let i = languages.length - 1; i >= 0; i--) { + if (languages[i].includes('_')) { + let languageWithoutCountryCode = languages[i].substring(0, 2); + + if (!languages.includes(languageWithoutCountryCode)) { + languages.splice(i + 1, 0, languageWithoutCountryCode); } } - languages.includes("en") || languages.push("en"); + } + languages.includes("en") || languages.push("en"); - languages.forEach((language, index) => index === languages.length - 1 ? importLocale(language, callback) : importLocale(language, () => {})); + languages.forEach((language, index) => index === languages.length - 1 ? importLocale(language, callback) : importLocale(language, () => {})); /* equals: languages.length === 1 && importLocale(languages[0], callback); languages.length === 2 && importLocale(languages[0], () => importLocale(languages[1], callback)); languages.length === 3 && importLocale(languages[0], () => importLocale(languages[1], () => importLocale(languages[2], callback))); ... */ // console.log(languages); - }); - } catch (error) { + });} catch (error) { // Finally, if code nor chrome://settings/languages are available, use window.navigator.language: let language = window.navigator.language.replace('-', '_'); diff --git a/menu/skeleton-parts/appearance.js b/menu/skeleton-parts/appearance.js index b3da19d60..9711cbef8 100644 --- a/menu/skeleton-parts/appearance.js +++ b/menu/skeleton-parts/appearance.js @@ -838,11 +838,10 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { click: function () { setTimeout(() => { if (satus.storage.get('related_videos')==="Titles" - && satus.storage.get("relatedVideosPrev") ==="Titles") { - if (!satus.storage.get('thumbnails_right')) { - this.nextSibling.nextSibling.click(); - satus.storage.set('relatedVideosPrev', "notTitles") - } + && satus.storage.get("relatedVideosPrev") ==="Titles") {if (!satus.storage.get('thumbnails_right')) { + this.nextSibling.nextSibling.click(); + satus.storage.set('relatedVideosPrev', "notTitles") + } } }, 650) @@ -867,15 +866,13 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { value: false, id: 'transcript', on: { - click: function () { - setTimeout(() => { - if (satus.storage.get('transcript')) { - if (satus.storage.get('no_page_margin')) { - this.nextSibling.nextSibling.click(); - } + click: function () { setTimeout(() => { + if (satus.storage.get('transcript')) { + if (satus.storage.get('no_page_margin')) { + this.nextSibling.nextSibling.click(); } - }, 250); - } + } + }, 250); } } }, compact_spacing: { @@ -889,15 +886,13 @@ extension.skeleton.main.layers.section.appearance.on.click.sidebar = { value: false, on: { - click: function () { - setTimeout(() => { - if (satus.storage.get('no_page_margin')) { - if (satus.storage.get('transcript')) { - this.previousSibling.previousSibling.click(); - } + click: function () { setTimeout(() => { + if (satus.storage.get('no_page_margin')) { + if (satus.storage.get('transcript')) { + this.previousSibling.previousSibling.click(); } - }, 250); - } + } + }, 250); } } }, chapters: { diff --git a/menu/skeleton-parts/general.js b/menu/skeleton-parts/general.js index a12841953..4fdf67374 100644 --- a/menu/skeleton-parts/general.js +++ b/menu/skeleton-parts/general.js @@ -229,15 +229,13 @@ extension.skeleton.main.layers.section.general = { component: 'switch', text: 'markWatchedVideos', on: { - click: function () { - setTimeout(() => { - if (satus.storage.get('mark_watched_videos')) { - if (!satus.storage.get('track_watched_videos')) { - this.nextSibling.click(); - } + click: function () { setTimeout(() => { + if (satus.storage.get('mark_watched_videos')) { + if (!satus.storage.get('track_watched_videos')) { + this.nextSibling.click(); } - }, 250); - } + } + }, 250); } } }, track_watched_videos: {