layout.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import type { Event } from "@billjs/event-emitter";
  2. import type { FeatureConfig } from "../types";
  3. import { scriptInfo } from "../constants";
  4. import { getFeatures } from "../config";
  5. import { addGlobalStyle, addParent, autoPlural, error, getAssetUrl, insertAfter, log, onSelectorExists, openInNewTab, pauseFor } from "../utils";
  6. import { getEvtData, siteEvents } from "../events";
  7. import { openMenu } from "./menu/menu_old";
  8. import { getGeniusUrl, createLyricsBtn, sanitizeArtists, sanitizeSong, getLyricsCacheEntry } from "./lyrics";
  9. import "./layout.css";
  10. let features: FeatureConfig;
  11. export async function preInitLayout() {
  12. features = await getFeatures();
  13. }
  14. //#MARKER BYTM-Config buttons
  15. /** Adds a watermark beneath the logo */
  16. export function addWatermark() {
  17. const watermark = document.createElement("a");
  18. watermark.role = "button";
  19. watermark.id = "betterytm-watermark";
  20. watermark.className = "style-scope ytmusic-nav-bar";
  21. watermark.innerText = scriptInfo.name;
  22. watermark.title = "Open menu";
  23. watermark.tabIndex = 1000;
  24. watermark.addEventListener("click", (e) => {
  25. e.stopPropagation();
  26. openMenu();
  27. });
  28. // when using the tab key to navigate
  29. watermark.addEventListener("keydown", (e) => {
  30. if(e.key === "Enter") {
  31. e.stopPropagation();
  32. openMenu();
  33. }
  34. });
  35. const logoElem = document.querySelector("#left-content") as HTMLElement;
  36. insertAfter(logoElem, watermark);
  37. log("Added watermark element", watermark);
  38. }
  39. /** Called whenever the menu exists to add a BYTM-Configuration button */
  40. export function addConfigMenuOption(container: HTMLElement) {
  41. const cfgOptElem = document.createElement("a");
  42. cfgOptElem.role = "button";
  43. cfgOptElem.className = "bytm-cfg-menu-option bytm-anchor";
  44. cfgOptElem.ariaLabel = "Click to open BetterYTM's configuration menu";
  45. const cfgOptItemElem = document.createElement("div");
  46. cfgOptItemElem.className = "bytm-cfg-menu-option-item";
  47. cfgOptItemElem.addEventListener("click", () => {
  48. const settingsBtnElem = document.querySelector<HTMLElement>("ytmusic-nav-bar ytmusic-settings-button tp-yt-paper-icon-button");
  49. settingsBtnElem?.click();
  50. openMenu();
  51. });
  52. const cfgOptIconElem = document.createElement("img");
  53. cfgOptIconElem.className = "bytm-cfg-menu-option-icon";
  54. cfgOptIconElem.src = getAssetUrl("icon/icon.png");
  55. const cfgOptTextElem = document.createElement("div");
  56. cfgOptTextElem.className = "bytm-cfg-menu-option-text";
  57. cfgOptTextElem.innerText = "BetterYTM Configuration";
  58. cfgOptItemElem.appendChild(cfgOptIconElem);
  59. cfgOptItemElem.appendChild(cfgOptTextElem);
  60. cfgOptElem.appendChild(cfgOptItemElem);
  61. container.appendChild(cfgOptElem);
  62. log("Added BYTM-Configuration button to menu popover", cfgOptElem);
  63. }
  64. //#MARKER remove upgrade tab
  65. /** Removes the "Upgrade" / YT Music Premium tab from the sidebar */
  66. export function removeUpgradeTab() {
  67. onSelectorExists("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer:nth-child(4)", (tabElemLarge) => {
  68. tabElemLarge.remove();
  69. log("Removed large upgrade tab");
  70. });
  71. onSelectorExists("ytmusic-app-layout #mini-guide ytmusic-guide-renderer #sections ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer:nth-child(4)", (tabElemSmall) => {
  72. tabElemSmall.remove();
  73. log("Removed small upgrade tab");
  74. });
  75. }
  76. //#MARKER volume slider
  77. /** Sets the volume slider to a set size */
  78. export function setVolSliderSize() {
  79. const { volumeSliderSize: size } = features;
  80. if(typeof size !== "number" || isNaN(Number(size)))
  81. return;
  82. const style = `\
  83. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  84. width: ${size}px !important;
  85. }`;
  86. addGlobalStyle(style, "vol-slider");
  87. }
  88. /** Sets the `step` attribute of the volume slider */
  89. export function setVolSliderStep() {
  90. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider") as HTMLInputElement;
  91. sliderElem.setAttribute("step", String(features.volumeSliderStep));
  92. }
  93. //#MARKER queue buttons
  94. export function initQueueButtons() {
  95. const addQueueBtns = (evt: Event) => {
  96. let amt = 0;
  97. for(const queueItm of getEvtData<HTMLElement>(evt).childNodes as NodeListOf<HTMLElement>) {
  98. if(!queueItm.classList.contains("bytm-has-queue-btns")) {
  99. addQueueButtons(queueItm);
  100. amt++;
  101. }
  102. }
  103. if(amt > 0)
  104. log(`Added buttons to ${amt} new queue ${autoPlural("item", amt)}`);
  105. };
  106. siteEvents.on("queueChanged", addQueueBtns);
  107. siteEvents.on("autoplayQueueChanged", addQueueBtns);
  108. const queueItems = document.querySelectorAll("#contents.ytmusic-player-queue > ytmusic-player-queue-item");
  109. if(queueItems.length === 0)
  110. return;
  111. queueItems.forEach(itm => addQueueButtons(itm as HTMLElement));
  112. log(`Added buttons to ${queueItems.length} existing queue ${autoPlural("item", queueItems)}`);
  113. }
  114. /**
  115. * Adds the buttons to each item in the current song queue.
  116. * Also observes for changes to add new buttons to new items in the queue.
  117. * TODO:FIXME: deleting an element from the queue shifts the lyrics buttons
  118. * @param queueItem The element with tagname `ytmusic-player-queue-item` to add queue buttons to
  119. */
  120. async function addQueueButtons(queueItem: HTMLElement) {
  121. //#SECTION general queue item stuff
  122. const queueBtnsCont = document.createElement("div");
  123. queueBtnsCont.className = "bytm-queue-btn-container";
  124. const songInfo = queueItem.querySelector(".song-info") as HTMLElement;
  125. if(!songInfo)
  126. return false;
  127. const [songEl, artistEl] = (songInfo.querySelectorAll("yt-formatted-string") as NodeListOf<HTMLElement>);
  128. const song = songEl.innerText;
  129. const artist = artistEl.innerText;
  130. if(!song || !artist)
  131. return false;
  132. //#SECTION lyrics btn
  133. const lyricsBtnElem = createLyricsBtn(undefined, false);
  134. {
  135. lyricsBtnElem.title = "Open this song's lyrics in a new tab";
  136. lyricsBtnElem.style.display = "inline-flex";
  137. lyricsBtnElem.style.visibility = "initial";
  138. lyricsBtnElem.style.pointerEvents = "initial";
  139. lyricsBtnElem.addEventListener("click", async (e) => {
  140. e.stopPropagation();
  141. let lyricsUrl: string | undefined;
  142. const artistsSan = sanitizeArtists(artist);
  143. const songSan = sanitizeSong(song);
  144. const cachedLyricsUrl = getLyricsCacheEntry(artistsSan, songSan);
  145. if(cachedLyricsUrl)
  146. lyricsUrl = cachedLyricsUrl;
  147. else if(!songInfo.hasAttribute("data-bytm-loading")) {
  148. const imgEl = lyricsBtnElem.querySelector("img") as HTMLImageElement;
  149. if(!cachedLyricsUrl) {
  150. songInfo.setAttribute("data-bytm-loading", "");
  151. imgEl.src = getAssetUrl("spinner.svg");
  152. imgEl.classList.add("bytm-spinner");
  153. }
  154. lyricsUrl = cachedLyricsUrl ?? await getGeniusUrl(artistsSan, songSan);
  155. const resetImgElem = () => {
  156. imgEl.src = getAssetUrl("lyrics.svg");
  157. imgEl.classList.remove("bytm-spinner");
  158. };
  159. if(!cachedLyricsUrl) {
  160. songInfo.removeAttribute("data-bytm-loading");
  161. // so the new image doesn't "blink"
  162. setTimeout(resetImgElem, 100);
  163. }
  164. if(!lyricsUrl) {
  165. resetImgElem();
  166. if(confirm("Couldn't find a lyrics page for this song.\nDo you want to open genius.com to manually search for it?"))
  167. openInNewTab("https://genius.com/search");
  168. return;
  169. }
  170. }
  171. lyricsUrl && openInNewTab(lyricsUrl);
  172. });
  173. }
  174. //#SECTION delete from queue btn
  175. const deleteBtnElem = document.createElement("a");
  176. {
  177. Object.assign(deleteBtnElem, {
  178. title: "Remove this song from the queue",
  179. className: "ytmusic-player-bar bytm-delete-from-queue bytm-generic-btn",
  180. role: "button",
  181. });
  182. deleteBtnElem.style.visibility = "initial";
  183. deleteBtnElem.addEventListener("click", async (e) => {
  184. e.stopPropagation();
  185. // container of the queue item popup menu - element gets reused for every queue item
  186. let queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown") as HTMLElement;
  187. try {
  188. // three dots button to open the popup menu of a queue item
  189. const dotsBtnElem = queueItem.querySelector("ytmusic-menu-renderer yt-button-shape button") as HTMLButtonElement;
  190. if(queuePopupCont)
  191. queuePopupCont.setAttribute("data-bytm-hidden", "true");
  192. dotsBtnElem.click();
  193. await pauseFor(25);
  194. queuePopupCont = document.querySelector("ytmusic-app ytmusic-popup-container tp-yt-iron-dropdown") as HTMLElement;
  195. if(!queuePopupCont.hasAttribute("data-bytm-hidden"))
  196. queuePopupCont.setAttribute("data-bytm-hidden", "true");
  197. // a little bit janky and unreliable but the only way afaik
  198. const removeFromQueueBtn = queuePopupCont.querySelector("tp-yt-paper-listbox *[role=option]:nth-child(7)") as HTMLElement;
  199. await pauseFor(20);
  200. removeFromQueueBtn.click();
  201. }
  202. catch(err) {
  203. error("Couldn't remove song from queue due to error:", err);
  204. }
  205. finally {
  206. queuePopupCont?.removeAttribute("data-bytm-hidden");
  207. }
  208. });
  209. const imgElem = document.createElement("img");
  210. imgElem.className = "bytm-generic-btn-img";
  211. imgElem.src = getAssetUrl("delete.svg");
  212. deleteBtnElem.appendChild(imgElem);
  213. }
  214. //#SECTION append elements to DOM
  215. queueBtnsCont.appendChild(lyricsBtnElem);
  216. queueBtnsCont.appendChild(deleteBtnElem);
  217. songInfo.appendChild(queueBtnsCont);
  218. queueItem.classList.add("bytm-has-queue-btns");
  219. return true;
  220. }
  221. //#MARKER better clickable stuff
  222. // TODO: add to thumbnails in "songs" list on channel pages (/channel/$id)
  223. // TODO: add to thumbnails in playlists (/playlist?list=$id)
  224. /** Adds anchors around elements and tweaks existing ones so songs are easier to open in a new tab */
  225. export function addAnchorImprovements() {
  226. //#SECTION carousel shelves
  227. try {
  228. // home page
  229. /** Only adds anchor improvements for carousel shelves that contain the regular list-item-renderer, not the two-row-item-renderer */
  230. const condCarouselImprovements = (el: HTMLElement) => {
  231. const listItemRenderer = el.querySelector("ytmusic-responsive-list-item-renderer");
  232. if(listItemRenderer) {
  233. const itemsElem = el.querySelector<HTMLElement>("ul#items");
  234. if(itemsElem) {
  235. const improvedElems = improveCarouselAnchors(itemsElem);
  236. improvedElems > 0 && log(`Added anchor improvements to ${improvedElems} carousel shelf ${autoPlural("item", improvedElems)}`);
  237. }
  238. }
  239. };
  240. // initial three shelves aren't included in the event fire
  241. onSelectorExists("ytmusic-carousel-shelf-renderer", () => {
  242. const carouselShelves = document.body.querySelectorAll<HTMLElement>("ytmusic-carousel-shelf-renderer");
  243. carouselShelves.forEach(condCarouselImprovements);
  244. });
  245. // every shelf that's loaded by scrolling:
  246. siteEvents.on("carouselShelvesChanged", (evt) => {
  247. const { addedNodes, removedNodes } = getEvtData<Record<"addedNodes" | "removedNodes", NodeListOf<HTMLElement>>>(evt);
  248. void removedNodes;
  249. if(addedNodes.length > 0)
  250. addedNodes.forEach(condCarouselImprovements);
  251. });
  252. // related tab in /watch
  253. // TODO: items are lazy-loaded so this needs to be done differently
  254. // maybe the onSelectorExists feature can be expanded to conditionally support continuous checking & querySelectorAll
  255. const relatedTabAnchorImprovements = (tabElem: HTMLElement) => {
  256. const relatedCarouselShelves = tabElem?.querySelectorAll<HTMLElement>("ytmusic-carousel-shelf-renderer");
  257. if(relatedCarouselShelves)
  258. relatedCarouselShelves.forEach(condCarouselImprovements);
  259. };
  260. const relatedTabContentsSelector = "ytmusic-section-list-renderer[page-type=\"MUSIC_PAGE_TYPE_TRACK_RELATED\"] #contents";
  261. onSelectorExists("ytmusic-tab-renderer[page-type=\"MUSIC_PAGE_TYPE_TRACK_RELATED\"]", (relatedTabContainer) => {
  262. const relatedTabObserver = new MutationObserver(([ { addedNodes, removedNodes } ]) => {
  263. if(addedNodes.length > 0 || removedNodes.length > 0)
  264. relatedTabAnchorImprovements(document.querySelector<HTMLElement>(relatedTabContentsSelector)!);
  265. });
  266. relatedTabObserver.observe(relatedTabContainer, {
  267. childList: true,
  268. });
  269. });
  270. onSelectorExists(relatedTabContentsSelector, (relatedTabContents) => {
  271. relatedTabAnchorImprovements(relatedTabContents);
  272. });
  273. }
  274. catch(err) {
  275. error("Couldn't improve carousel shelf anchors due to an error:", err);
  276. }
  277. //#SECTION sidebar
  278. try {
  279. const addSidebarAnchors = (sidebarCont: HTMLElement) => {
  280. const items = sidebarCont.parentNode!.querySelectorAll<HTMLElement>("ytmusic-guide-entry-renderer tp-yt-paper-item");
  281. improveSidebarAnchors(items);
  282. return items.length;
  283. };
  284. onSelectorExists("ytmusic-app-layout tp-yt-app-drawer #contentContainer #guide-content #items ytmusic-guide-entry-renderer", (sidebarCont) => {
  285. const itemsAmt = addSidebarAnchors(sidebarCont);
  286. log(`Added anchors around ${itemsAmt} sidebar ${autoPlural("item", itemsAmt)}`);
  287. });
  288. onSelectorExists("ytmusic-app-layout #mini-guide ytmusic-guide-renderer ytmusic-guide-section-renderer #items ytmusic-guide-entry-renderer", (miniSidebarCont) => {
  289. const itemsAmt = addSidebarAnchors(miniSidebarCont);
  290. log(`Added anchors around ${itemsAmt} mini sidebar ${autoPlural("item", itemsAmt)}`);
  291. });
  292. }
  293. catch(err) {
  294. error("Couldn't add anchors to sidebar items due to an error:", err);
  295. }
  296. }
  297. const sidebarPaths = [
  298. "/",
  299. "/explore",
  300. "/library",
  301. ];
  302. /**
  303. * Adds anchors to the sidebar items so they can be opened in a new tab
  304. * @param sidebarItem
  305. */
  306. function improveSidebarAnchors(sidebarItems: NodeListOf<HTMLElement>) {
  307. sidebarItems.forEach((item, i) => {
  308. const anchorElem = document.createElement("a");
  309. anchorElem.className = "bytm-anchor";
  310. anchorElem.role = "button";
  311. anchorElem.target = "_self";
  312. anchorElem.href = sidebarPaths[i] ?? "#";
  313. anchorElem.title = "Middle click to open in a new tab";
  314. anchorElem.addEventListener("click", (e) => {
  315. e.preventDefault();
  316. });
  317. addParent(item, anchorElem);
  318. });
  319. }
  320. /**
  321. * Actually adds the anchor improvements to carousel shelf items
  322. * @param itemsElement The container with the selector `ul#items` inside of each `ytmusic-carousel`
  323. */
  324. function improveCarouselAnchors(itemsElement: HTMLElement) {
  325. if(itemsElement.classList.contains("bytm-anchors-improved"))
  326. return 0;
  327. let improvedElems = 0;
  328. try {
  329. const allListItems = itemsElement.querySelectorAll<HTMLElement>("ytmusic-responsive-list-item-renderer");
  330. for(const listItem of allListItems) {
  331. const thumbnailElem = listItem.querySelector<HTMLElement>(".left-items");
  332. const titleElem = listItem.querySelector<HTMLAnchorElement>(".title-column yt-formatted-string.title a");
  333. if(!thumbnailElem || !titleElem) {
  334. error("Couldn't add carousel shelf anchor improvements because either the thumbnail or title element couldn't be found");
  335. continue;
  336. }
  337. const thumbnailAnchor = document.createElement("a");
  338. thumbnailAnchor.className = "bytm-carousel-shelf-anchor bytm-anchor";
  339. thumbnailAnchor.href = titleElem.href;
  340. thumbnailAnchor.target = "_self";
  341. thumbnailAnchor.role = "button";
  342. thumbnailAnchor.addEventListener("click", (e) => {
  343. e.preventDefault();
  344. });
  345. addParent(thumbnailElem, thumbnailAnchor);
  346. improvedElems++;
  347. }
  348. }
  349. catch(err) {
  350. error("Couldn't add anchor improvements due to error:", err);
  351. }
  352. finally {
  353. itemsElement.classList.add("bytm-anchors-improved");
  354. }
  355. return improvedElems;
  356. }