YouTube Sub Feed Filter 2

Filters your YouTube subscriptions feed.

当前为 2024-08-06 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube Sub Feed Filter 2
  3. // @version 1.34
  4. // @description Filters your YouTube subscriptions feed.
  5. // @author Callum Latham
  6. // @namespace https://greasyfork.org/users/696211-ctl2
  7. // @license MIT
  8. // @match *://www.youtube.com/*
  9. // @match *://youtube.com/*
  10. // @exclude *://www.youtube.com/embed/*
  11. // @exclude *://youtube.com/embed/*
  12. // @require https://update.greasyfork.org/scripts/446506/1419559/%24Config.js
  13. // @grant GM.setValue
  14. // @grant GM.getValue
  15. // @grant GM.deleteValue
  16. // ==/UserScript==
  17.  
  18. /* global $Config */
  19.  
  20. // Don't run in frames (e.g. stream chat frame)
  21. if (window.parent !== window) {
  22. // noinspection JSAnnotator
  23. return;
  24. }
  25.  
  26. // User config
  27.  
  28. const LONG_PRESS_TIME = 400;
  29. const REGEXP_FLAGS = 'i';
  30.  
  31. // Dev config
  32.  
  33. const VIDEO_TYPE_IDS = {
  34. GROUPS: {
  35. ALL: 'All',
  36. STREAMS: 'Streams',
  37. PREMIERES: 'Premieres',
  38. NONE: 'None',
  39. },
  40. INDIVIDUALS: {
  41. STREAMS_SCHEDULED: 'Scheduled Streams',
  42. STREAMS_LIVE: 'Live Streams',
  43. STREAMS_FINISHED: 'Finished Streams',
  44. PREMIERES_SCHEDULED: 'Scheduled Premieres',
  45. PREMIERES_LIVE: 'Live Premieres',
  46. SHORTS: 'Shorts',
  47. FUNDRAISERS: 'Fundraisers',
  48. NORMAL: 'Basic Videos',
  49. },
  50. };
  51.  
  52. const CUTOFF_VALUES = [
  53. 'Minimum',
  54. 'Maximum',
  55. ];
  56.  
  57. const BADGE_VALUES = [
  58. 'Exclude',
  59. 'Include',
  60. 'Require',
  61. ];
  62.  
  63. const TITLE = 'YouTube Sub Feed Filter';
  64.  
  65. function getVideoTypes(children) {
  66. const registry = new Set();
  67. const register = (value) => {
  68. if (registry.has(value)) {
  69. throw new Error(`Overlap found at '${value}'.`);
  70. }
  71. registry.add(value);
  72. };
  73. for (const {value} of children) {
  74. switch (value) {
  75. case VIDEO_TYPE_IDS.GROUPS.ALL:
  76. Object.values(VIDEO_TYPE_IDS.INDIVIDUALS).forEach(register);
  77. break;
  78. case VIDEO_TYPE_IDS.GROUPS.STREAMS:
  79. register(VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_SCHEDULED);
  80. register(VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_LIVE);
  81. register(VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_FINISHED);
  82. break;
  83. case VIDEO_TYPE_IDS.GROUPS.PREMIERES:
  84. register(VIDEO_TYPE_IDS.INDIVIDUALS.PREMIERES_SCHEDULED);
  85. register(VIDEO_TYPE_IDS.INDIVIDUALS.PREMIERES_LIVE);
  86. break;
  87. default:
  88. register(value);
  89. }
  90. }
  91. return registry;
  92. }
  93.  
  94. const $config = new $Config(
  95. 'YTSFF_TREE',
  96. (() => {
  97. const regexPredicate = (value) => {
  98. try {
  99. RegExp(value);
  100. } catch (_) {
  101. return 'Value must be a valid regular expression.';
  102. }
  103. return true;
  104. };
  105. const videoTypeOptions = Object.values({
  106. ...VIDEO_TYPE_IDS.GROUPS,
  107. ...VIDEO_TYPE_IDS.INDIVIDUALS,
  108. });
  109. return {
  110. children: [
  111. {
  112. label: 'Filters',
  113. children: [],
  114. seed: {
  115. label: 'Filter Name',
  116. value: '',
  117. children: [
  118. {
  119. label: 'Channel Regex',
  120. children: [],
  121. seed: {
  122. value: '^',
  123. predicate: regexPredicate,
  124. },
  125. },
  126. {
  127. label: 'Video Regex',
  128. children: [],
  129. seed: {
  130. value: '^',
  131. predicate: regexPredicate,
  132. },
  133. },
  134. {
  135. label: 'Video Types',
  136. children: [
  137. {
  138. value: VIDEO_TYPE_IDS.GROUPS.ALL,
  139. options: videoTypeOptions,
  140. },
  141. ],
  142. seed: {
  143. value: VIDEO_TYPE_IDS.GROUPS.NONE,
  144. options: videoTypeOptions,
  145. },
  146. childPredicate: (children) => {
  147. try {
  148. getVideoTypes(children);
  149. } catch ({message}) {
  150. return message;
  151. }
  152. return true;
  153. },
  154. },
  155. ],
  156. },
  157. },
  158. {
  159. label: 'Cutoffs',
  160. children: [
  161. {
  162. label: 'Watched (%)',
  163. children: [],
  164. seed: {
  165. childPredicate: ([{'value': boundary}, {value}]) => {
  166. if (boundary === CUTOFF_VALUES[0]) {
  167. return value < 100 ? true : 'Minimum must be less than 100%';
  168. }
  169. return value > 0 ? true : 'Maximum must be greater than 0%';
  170. },
  171. children: [
  172. {
  173. value: CUTOFF_VALUES[1],
  174. options: CUTOFF_VALUES,
  175. },
  176. {value: 100},
  177. ],
  178. },
  179. },
  180. {
  181. label: 'View Count',
  182. children: [],
  183. seed: {
  184. childPredicate: ([{'value': boundary}, {value}]) => {
  185. if (boundary === CUTOFF_VALUES[1]) {
  186. return value > 0 ? true : 'Maximum must be greater than 0';
  187. }
  188. return true;
  189. },
  190. children: [
  191. {
  192. value: CUTOFF_VALUES[0],
  193. options: CUTOFF_VALUES,
  194. },
  195. {
  196. value: 0,
  197. predicate: (value) => Math.floor(value) === value ? true : 'Value must be an integer',
  198. },
  199. ],
  200. },
  201. },
  202. {
  203. label: 'Duration (Minutes)',
  204. children: [],
  205. seed: {
  206. childPredicate: ([{'value': boundary}, {value}]) => {
  207. if (boundary === CUTOFF_VALUES[1]) {
  208. return value > 0 ? true : 'Maximum must be greater than 0';
  209. }
  210. return true;
  211. },
  212. children: [
  213. {
  214. value: CUTOFF_VALUES[0],
  215. options: CUTOFF_VALUES,
  216. },
  217. {value: 0},
  218. ],
  219. },
  220. },
  221. ],
  222. },
  223. {
  224. label: 'Badges',
  225. children: [
  226. {
  227. label: 'Verified',
  228. value: BADGE_VALUES[1],
  229. options: BADGE_VALUES,
  230. },
  231. {
  232. label: 'Official Artist',
  233. value: BADGE_VALUES[1],
  234. options: BADGE_VALUES,
  235. },
  236. ],
  237. },
  238. ],
  239. };
  240. })(),
  241. ([filters, cutoffs, badges]) => ({
  242. filters: (() => {
  243. const getRegex = ({children}) => new RegExp(children.length === 0 ?
  244. '' :
  245. children.map(({value}) => `(${value})`).join('|'), REGEXP_FLAGS);
  246. return filters.children.map(({'children': [channel, video, type]}) => ({
  247. channels: getRegex(channel),
  248. videos: getRegex(video),
  249. types: type.children.length === 0 ? Object.values(VIDEO_TYPE_IDS.INDIVIDUALS) : getVideoTypes(type.children),
  250. }));
  251. })(),
  252. cutoffs: cutoffs.children.map(({children}) => {
  253. const boundaries = [Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY];
  254. for (const {'children': [{'value': boundary}, {value}]} of children) {
  255. boundaries[boundary === CUTOFF_VALUES[0] ? 0 : 1] = value;
  256. }
  257. return boundaries;
  258. }),
  259. badges: badges.children.map(({value}) => BADGE_VALUES.indexOf(value)),
  260. }),
  261. TITLE,
  262. {
  263. headBase: '#c80000',
  264. headButtonExit: '#000000',
  265. borderHead: '#ffffff',
  266. nodeBase: ['#222222', '#111111'],
  267. borderTooltip: '#c80000',
  268. },
  269. {
  270. zIndex: 10000,
  271. scrollbarColor: 'initial',
  272. },
  273. );
  274.  
  275. const KEY_IS_ACTIVE = 'YTSFF_IS_ACTIVE';
  276.  
  277. // Removing row styling
  278. (() => {
  279. const styleElement = document.createElement('style');
  280. document.head.appendChild(styleElement);
  281. const styleSheet = styleElement.sheet;
  282. const rules = [['[page-subtype=subscriptions] ytd-rich-section-renderer:not(:first-child)', [['display', 'none']]]];
  283. for (let rule of rules) {
  284. styleSheet.insertRule(`${rule[0]}{${rule[1].map(([property, value]) => `${property}:${value} !important;`).join('')}}`);
  285. }
  286. })();
  287.  
  288. // Video element helpers
  289.  
  290. function getSubPage() {
  291. return document.querySelector('.ytd-page-manager[page-subtype="subscriptions"]');
  292. }
  293.  
  294. function getAllVideos() {
  295. const subPage = getSubPage();
  296. return [...subPage.querySelectorAll('ytd-rich-item-renderer')];
  297. }
  298.  
  299. function firstWordEquals(element, word) {
  300. return element.innerText.split(' ')[0] === word;
  301. }
  302.  
  303. function getVideoBadges(video) {
  304. return video.querySelectorAll('.video-badge');
  305. }
  306.  
  307. function getChannelBadges(video) {
  308. const container = video.querySelector('ytd-badge-supported-renderer.ytd-channel-name');
  309. return container ? [...container.querySelectorAll('.badge')] : [];
  310. }
  311.  
  312. function getMetadataLine(video) {
  313. return video.querySelector('#metadata-line');
  314. }
  315.  
  316. function isScheduled(video) {
  317. return VIDEO_PREDICATES[VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_SCHEDULED](video)
  318. || VIDEO_PREDICATES[VIDEO_TYPE_IDS.INDIVIDUALS.PREMIERES_SCHEDULED](video);
  319. }
  320.  
  321. function getUploadTimeNode(video) {
  322. const children = [...getMetadataLine(video).children].filter((child) => child.matches('.inline-metadata-item'));
  323. return children.length > 1 ? children[1] : null;
  324. }
  325.  
  326. // Config testers
  327.  
  328. const VIDEO_PREDICATES = {
  329. [VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_SCHEDULED]: (video) => {
  330. const metadataLine = getMetadataLine(video);
  331. return firstWordEquals(metadataLine, 'Scheduled');
  332. },
  333. [VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_LIVE]: (video) => {
  334. for (const badge of getVideoBadges(video)) {
  335. if (firstWordEquals(badge, 'LIVE')) {
  336. return true;
  337. }
  338. }
  339. return false;
  340. },
  341. [VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_FINISHED]: (video) => {
  342. const uploadTimeNode = getUploadTimeNode(video);
  343. return uploadTimeNode && firstWordEquals(uploadTimeNode, 'Streamed');
  344. },
  345. [VIDEO_TYPE_IDS.INDIVIDUALS.PREMIERES_SCHEDULED]: (video) => {
  346. const metadataLine = getMetadataLine(video);
  347. return firstWordEquals(metadataLine, 'Premieres');
  348. },
  349. [VIDEO_TYPE_IDS.INDIVIDUALS.PREMIERES_LIVE]: (video) => {
  350. for (const badge of getVideoBadges(video)) {
  351. if (firstWordEquals(badge, 'PREMIERING') || firstWordEquals(badge, 'PREMIERE')) {
  352. return true;
  353. }
  354. }
  355. return false;
  356. },
  357. [VIDEO_TYPE_IDS.INDIVIDUALS.SHORTS]: (video) => {
  358. return video.querySelector('ytd-rich-grid-slim-media')?.isShort ?? false;
  359. },
  360. [VIDEO_TYPE_IDS.INDIVIDUALS.NORMAL]: (video) => {
  361. const uploadTimeNode = getUploadTimeNode(video);
  362. return uploadTimeNode ? new RegExp('^\\d+ .+ ago$').test(uploadTimeNode.innerText) : false;
  363. },
  364. [VIDEO_TYPE_IDS.INDIVIDUALS.FUNDRAISERS]: (video) => {
  365. for (const badge of getVideoBadges(video)) {
  366. if (firstWordEquals(badge, 'Fundraiser')) {
  367. return true;
  368. }
  369. }
  370. return false;
  371. },
  372. };
  373.  
  374. const CUTOFF_GETTERS = [
  375. // Watched %
  376. (video) => {
  377. const progressBar = video.querySelector('#progress');
  378. if (!progressBar) {
  379. return 0;
  380. }
  381. return Number.parseInt(progressBar.style.width.slice(0, -1));
  382. },
  383. // View count
  384. (video) => {
  385. if (isScheduled(video)) {
  386. return 0;
  387. }
  388. const {innerText} = [...getMetadataLine(video).children].find((child) => child.matches('.inline-metadata-item'));
  389. const [valueString] = innerText.split(' ');
  390. const lastChar = valueString.slice(-1);
  391. if (/\d/.test(lastChar)) {
  392. return Number.parseInt(valueString);
  393. }
  394. const valueNumber = Number.parseFloat(valueString.slice(0, -1));
  395. switch (lastChar) {
  396. case 'B':
  397. return valueNumber * 1000000000;
  398. case 'M':
  399. return valueNumber * 1000000;
  400. case 'K':
  401. return valueNumber * 1000;
  402. }
  403. return valueNumber;
  404. },
  405. // Duration (minutes)
  406. (video) => {
  407. const timeElement = video.querySelector('ytd-thumbnail-overlay-time-status-renderer');
  408. let minutes = 0;
  409. if (timeElement) {
  410. const timeParts = timeElement.innerText.split(':').map((_) => Number.parseInt(_));
  411. let timeValue = 1 / 60;
  412. for (let i = timeParts.length - 1; i >= 0; --i) {
  413. minutes += timeParts[i] * timeValue;
  414. timeValue *= 60;
  415. }
  416. }
  417. return Number.isNaN(minutes) ? 0 : minutes;
  418. },
  419. ];
  420.  
  421. const BADGE_PREDICATES = [
  422. // Verified
  423. (video) => getChannelBadges(video)
  424. .some((badge) => badge.classList.contains('badge-style-type-verified')),
  425. // Official Artist
  426. (video) => getChannelBadges(video)
  427. .some((badge) => badge.classList.contains('badge-style-type-verified-artist')),
  428. ];
  429.  
  430. // Hider functions
  431.  
  432. function loadVideo(video) {
  433. return new Promise((resolve) => {
  434. const test = () => {
  435. if (video.querySelector('#interaction.yt-icon-button')) {
  436. observer.disconnect();
  437. resolve();
  438. }
  439. };
  440. const observer = new MutationObserver(test);
  441. observer.observe(video, {
  442. childList: true,
  443. subtree: true,
  444. attributes: true,
  445. attributeOldValue: true,
  446. });
  447. test();
  448. });
  449. }
  450.  
  451. function shouldHide({filters, cutoffs, badges}, video) {
  452. for (let i = 0; i < BADGE_PREDICATES.length; ++i) {
  453. if (badges[i] !== 1 && Boolean(badges[i]) !== BADGE_PREDICATES[i](video)) {
  454. return true;
  455. }
  456. }
  457. for (let i = 0; i < CUTOFF_GETTERS.length; ++i) {
  458. const [lowerBound, upperBound] = cutoffs[i];
  459. const value = CUTOFF_GETTERS[i](video);
  460. if (value < lowerBound || value > upperBound) {
  461. return true;
  462. }
  463. }
  464. const channelName = video.querySelector('ytd-channel-name#channel-name')?.innerText;
  465. const videoName = video.querySelector('#video-title').innerText;
  466. for (const {'channels': channelRegex, 'videos': videoRegex, types} of filters) {
  467. if (
  468. (!channelName || channelRegex.test(channelName))
  469. && videoRegex.test(videoName)
  470. ) {
  471. for (const type of types) {
  472. if (VIDEO_PREDICATES[type](video)) {
  473. return true;
  474. }
  475. }
  476. }
  477. }
  478. return false;
  479. }
  480.  
  481. const hideList = (() => {
  482. const list = [];
  483. let hasReverted = true;
  484. function hide(element, doHide) {
  485. element.hidden = false;
  486. if (doHide) {
  487. element.style.display = 'none';
  488. } else {
  489. element.style.removeProperty('display');
  490. }
  491. }
  492. return {
  493. 'add'(doAct, element, doHide = true) {
  494. if (doAct) {
  495. hasReverted = false;
  496. }
  497. list.push({element, doHide, wasHidden: element.hidden});
  498. if (doAct) {
  499. hide(element, doHide);
  500. }
  501. },
  502. 'revert'(doErase) {
  503. if (!hasReverted) {
  504. hasReverted = true;
  505. for (const {element, doHide, wasHidden} of list) {
  506. hide(element, !doHide);
  507. element.hidden = wasHidden;
  508. }
  509. }
  510. if (doErase) {
  511. list.length = 0;
  512. }
  513. },
  514. 'ensure'() {
  515. if (!hasReverted) {
  516. return;
  517. }
  518. hasReverted = false;
  519. for (const {element, doHide} of list) {
  520. hide(element, doHide);
  521. }
  522. },
  523. };
  524. })();
  525.  
  526. async function hideVideos(doAct, videos = getAllVideos()) {
  527. const config = $config.get();
  528. for (const video of videos) {
  529. await new Promise(async (resolve) => {
  530. await loadVideo(video);
  531. if (shouldHide(config, video)) {
  532. hideList.add(doAct, video);
  533. }
  534. resolve();
  535. });
  536. // Allow the page to update visually before moving on
  537. await new Promise((resolve) => {
  538. window.setTimeout(resolve, 0);
  539. });
  540. }
  541. }
  542.  
  543. // Helpers
  544.  
  545. function hideFromMutations(isActive, mutations) {
  546. const videos = [];
  547. for (const {addedNodes} of mutations) {
  548. for (const node of addedNodes) {
  549. if (node.tagName === 'YTD-RICH-ITEM-RENDERER') {
  550. videos.push(node);
  551. }
  552. }
  553. }
  554. hideVideos(isActive(), videos);
  555. }
  556.  
  557. function resetConfig(fullReset = true) {
  558. hideList.revert(fullReset);
  559. }
  560.  
  561. function getButtonDock() {
  562. return document
  563. .querySelector('ytd-browse[page-subtype="subscriptions"]')
  564. .querySelector('#contents')
  565. .querySelector('#title-container')
  566. .querySelector('#top-level-buttons-computed');
  567. }
  568.  
  569. // Button
  570.  
  571. class ClickHandler {
  572. constructor(button, onShortClick, onLongClick) {
  573. this.onShortClick = function () {
  574. onShortClick();
  575. window.clearTimeout(this.longClickTimeout);
  576. window.removeEventListener('mouseup', this.onShortClick);
  577. }.bind(this);
  578. this.onLongClick = function () {
  579. window.removeEventListener('mouseup', this.onShortClick);
  580. onLongClick();
  581. }.bind(this);
  582. this.longClickTimeout = window.setTimeout(this.onLongClick, LONG_PRESS_TIME);
  583. window.addEventListener('mouseup', this.onShortClick);
  584. }
  585. }
  586.  
  587. class Button {
  588. wasActive;
  589. isActive = false;
  590. isDormant = false;
  591. constructor() {
  592. this.element = (() => {
  593. const getSVG = () => {
  594. const svgNamespace = 'http://www.w3.org/2000/svg';
  595. const bottom = document.createElementNS(svgNamespace, 'path');
  596. bottom.setAttribute('d', 'M128.25,175.6c1.7,1.8,2.7,4.1,2.7,6.6v139.7l60-51.3v-88.4c0-2.5,1-4.8,2.7-6.6L295.15,65H26.75L128.25,175.6z');
  597. const top = document.createElementNS(svgNamespace, 'rect');
  598. top.setAttribute('x', '13.95');
  599. top.setAttribute('width', '294');
  600. top.setAttribute('height', '45');
  601. const g = document.createElementNS(svgNamespace, 'g');
  602. g.appendChild(bottom);
  603. g.appendChild(top);
  604. const svg = document.createElementNS(svgNamespace, 'svg');
  605. svg.setAttribute('viewBox', '-50 -50 400 400');
  606. svg.setAttribute('focusable', 'false');
  607. svg.appendChild(g);
  608. return svg;
  609. };
  610. const getNewButton = () => {
  611. const {parentElement, 'children': [, openerTemplate]} = getButtonDock();
  612. const button = openerTemplate.cloneNode(false);
  613. if (openerTemplate.innerText) {
  614. throw new Error('too early');
  615. }
  616. // 🤷‍♀️
  617. const policy = trustedTypes?.createPolicy('policy', {createHTML: (string) => string}) ?? {createHTML: (string) => string};
  618. parentElement.appendChild(button);
  619. button.innerHTML = policy.createHTML(openerTemplate.innerHTML);
  620. button.querySelector('yt-button-shape').innerHTML = policy.createHTML(openerTemplate.querySelector('yt-button-shape').innerHTML);
  621. parentElement.appendChild(button);
  622. button.innerHTML = openerTemplate.innerHTML;
  623. button.querySelector('yt-button-shape').innerHTML = openerTemplate.querySelector('yt-button-shape').innerHTML;
  624. button.querySelector('a').removeAttribute('href');
  625. button.querySelector('yt-icon').appendChild(getSVG());
  626. button.querySelector('tp-yt-paper-tooltip').remove();
  627. return button;
  628. };
  629. return getNewButton();
  630. })();
  631. this.element.addEventListener('mousedown', this.onMouseDown.bind(this));
  632. GM.getValue(KEY_IS_ACTIVE, true).then((isActive) => {
  633. this.isActive = isActive;
  634. this.update();
  635. const videoObserver = new MutationObserver(hideFromMutations.bind(null, () => this.isActive));
  636. videoObserver.observe(
  637. document.querySelector('ytd-browse[page-subtype="subscriptions"]').querySelector('div#contents'),
  638. {childList: true},
  639. );
  640. hideVideos(isActive);
  641. });
  642. let resizeCount = 0;
  643. window.addEventListener('resize', () => {
  644. const resizeId = ++resizeCount;
  645. this.forceInactive();
  646. const listener = ({detail}) => {
  647. // column size changed
  648. if (detail.actionName === 'yt-window-resized') {
  649. window.setTimeout(() => {
  650. if (resizeId !== resizeCount) {
  651. return;
  652. }
  653. this.forceInactive(false);
  654. // Don't bother re-running filters if the sub page isn't shown
  655. if (this.isDormant) {
  656. return;
  657. }
  658. resetConfig();
  659. hideVideos(this.isActive);
  660. }, 1000);
  661. document.body.removeEventListener('yt-action', listener);
  662. }
  663. };
  664. document.body.addEventListener('yt-action', listener);
  665. });
  666. }
  667. forceInactive(doForce = true) {
  668. if (doForce) {
  669. // if wasActive isn't undefined, forceInactive was already called
  670. if (this.wasActive === undefined) {
  671. // Saves a GM.getValue call later
  672. this.wasActive = this.isActive;
  673. this.isActive = false;
  674. }
  675. } else {
  676. this.isActive = this.wasActive;
  677. this.wasActive = undefined;
  678. }
  679. }
  680. update() {
  681. if (this.isActive) {
  682. this.setButtonActive();
  683. }
  684. }
  685. setButtonActive() {
  686. if (this.isActive) {
  687. this.element.querySelector('svg').style.setProperty('fill', 'var(--yt-spec-call-to-action)');
  688. } else {
  689. this.element.querySelector('svg').style.setProperty('fill', 'currentcolor');
  690. }
  691. }
  692. toggleActive() {
  693. this.isActive = !this.isActive;
  694. this.setButtonActive();
  695. GM.setValue(KEY_IS_ACTIVE, this.isActive);
  696. if (this.isActive) {
  697. hideList.ensure();
  698. } else {
  699. hideList.revert(false);
  700. }
  701. }
  702. async onLongClick() {
  703. await $config.edit();
  704. resetConfig();
  705. hideVideos(this.isActive);
  706. }
  707. onMouseDown(event) {
  708. if (event.button === 0) {
  709. new ClickHandler(this.element, this.toggleActive.bind(this), this.onLongClick.bind(this));
  710. }
  711. }
  712. }
  713.  
  714. // Main
  715.  
  716. (() => {
  717. let button;
  718. const loadButton = async () => {
  719. if (button) {
  720. button.isDormant = false;
  721. hideVideos(button.isActive);
  722. return;
  723. }
  724. try {
  725. await $config.ready();
  726. } catch (error) {
  727. if (!$config.reset) {
  728. throw error;
  729. }
  730. if (!window.confirm(`${error.message}\n\nWould you like to erase your data?`)) {
  731. return;
  732. }
  733. $config.reset();
  734. }
  735. try {
  736. getButtonDock();
  737. button = new Button();
  738. } catch (e) {
  739. const emitter = document.getElementById('page-manager');
  740. const bound = () => {
  741. loadButton();
  742. emitter.removeEventListener('yt-action', bound);
  743. };
  744. emitter.addEventListener('yt-action', bound);
  745. }
  746. };
  747. const isGridView = () => {
  748. return Boolean(
  749. document.querySelector('ytd-browse[page-subtype="subscriptions"]:not([hidden])')
  750. && document.querySelector('ytd-browse > ytd-two-column-browse-results-renderer ytd-rich-grid-renderer ytd-rich-item-renderer ytd-rich-grid-media'),
  751. );
  752. };
  753. function onNavigate({detail}) {
  754. if (detail.endpoint.browseEndpoint) {
  755. const {params, browseId} = detail.endpoint.browseEndpoint;
  756. // Handle navigation to the sub feed
  757. if ((params === 'MAE%3D' || (!params && (!button || isGridView()))) && browseId === 'FEsubscriptions') {
  758. const emitter = document.querySelector('ytd-app');
  759. const event = 'yt-action';
  760. if (button || isGridView()) {
  761. loadButton();
  762. } else {
  763. const listener = ({detail}) => {
  764. if (detail.actionName === 'ytd-update-grid-state-action') {
  765. if (isGridView()) {
  766. loadButton();
  767. }
  768. emitter.removeEventListener(event, listener);
  769. }
  770. };
  771. emitter.addEventListener(event, listener);
  772. }
  773. return;
  774. }
  775. }
  776. // Handle navigation away from the sub feed
  777. if (button) {
  778. button.isDormant = true;
  779. hideList.revert();
  780. }
  781. }
  782. document.body.addEventListener('yt-navigate-finish', onNavigate);
  783. })();