YouTube Sub Feed Filter 2

Filters your YouTube subscriptions feed.

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

  1. // ==UserScript==
  2. // @name YouTube Sub Feed Filter 2
  3. // @version 1.26
  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/1407081/%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 videoTypePredicate = 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. predicate: videoTypePredicate,
  140. },
  141. ],
  142. seed: {
  143. value: VIDEO_TYPE_IDS.GROUPS.NONE,
  144. predicate: videoTypePredicate,
  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. predicate: 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. predicate: 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. predicate: 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. predicate: BADGE_VALUES,
  230. },
  231. {
  232. label: 'Official Artist',
  233. value: BADGE_VALUES[1],
  234. predicate: 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: '#ff0000',
  264. headButtonExit: '#000000',
  265. borderHead: '#ffffff',
  266. nodeBase: ['#222222', '#111111'],
  267. borderTooltip: '#570000',
  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 = [
  283. ['ytd-rich-grid-row #contents.ytd-rich-grid-row', [['display', 'contents']]],
  284. ['ytd-rich-grid-row', [['display', 'contents']]],
  285. ];
  286. for (let rule of rules) {
  287. styleSheet.insertRule(`${rule[0]}{${rule[1].map(([property, value]) => `${property}:${value} !important;`).join('')}}`);
  288. }
  289. })();
  290.  
  291. // Video element helpers
  292.  
  293. function getSubPage() {
  294. return document.querySelector('.ytd-page-manager[page-subtype="subscriptions"]');
  295. }
  296.  
  297. function getAllRows() {
  298. const subPage = getSubPage();
  299. return subPage ? [...subPage.querySelectorAll('ytd-rich-grid-row')] : [];
  300. }
  301.  
  302. function getAllSections() {
  303. const subPage = getSubPage();
  304. return subPage ? [...subPage.querySelectorAll('ytd-rich-section-renderer:not(:first-child)')] : [];
  305. }
  306.  
  307. function getAllVideos(row) {
  308. return [...row.querySelectorAll('ytd-rich-item-renderer')];
  309. }
  310.  
  311. function firstWordEquals(element, word) {
  312. return element.innerText.split(' ')[0] === word;
  313. }
  314.  
  315. function getVideoBadges(video) {
  316. return video.querySelectorAll('.video-badge');
  317. }
  318.  
  319. function getChannelBadges(video) {
  320. const container = video.querySelector('ytd-badge-supported-renderer.ytd-channel-name');
  321. return container ? [...container.querySelectorAll('.badge')] : [];
  322. }
  323.  
  324. function getMetadataLine(video) {
  325. return video.querySelector('#metadata-line');
  326. }
  327.  
  328. function isScheduled(video) {
  329. return VIDEO_PREDICATES[VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_SCHEDULED](video)
  330. || VIDEO_PREDICATES[VIDEO_TYPE_IDS.INDIVIDUALS.PREMIERES_SCHEDULED](video);
  331. }
  332.  
  333. function getUploadTimeNode(video) {
  334. const children = [...getMetadataLine(video).children].filter((child) => child.matches('.inline-metadata-item'));
  335. return children.length > 1 ? children[1] : null;
  336. }
  337.  
  338. // Config testers
  339.  
  340. const VIDEO_PREDICATES = {
  341. [VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_SCHEDULED]: (video) => {
  342. const metadataLine = getMetadataLine(video);
  343. return firstWordEquals(metadataLine, 'Scheduled');
  344. },
  345. [VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_LIVE]: (video) => {
  346. for (const badge of getVideoBadges(video)) {
  347. if (firstWordEquals(badge, 'LIVE')) {
  348. return true;
  349. }
  350. }
  351. return false;
  352. },
  353. [VIDEO_TYPE_IDS.INDIVIDUALS.STREAMS_FINISHED]: (video) => {
  354. const uploadTimeNode = getUploadTimeNode(video);
  355. return uploadTimeNode && firstWordEquals(uploadTimeNode, 'Streamed');
  356. },
  357. [VIDEO_TYPE_IDS.INDIVIDUALS.PREMIERES_SCHEDULED]: (video) => {
  358. const metadataLine = getMetadataLine(video);
  359. return firstWordEquals(metadataLine, 'Premieres');
  360. },
  361. [VIDEO_TYPE_IDS.INDIVIDUALS.PREMIERES_LIVE]: (video) => {
  362. for (const badge of getVideoBadges(video)) {
  363. if (firstWordEquals(badge, 'PREMIERING') || firstWordEquals(badge, 'PREMIERE')) {
  364. return true;
  365. }
  366. }
  367. return false;
  368. },
  369. [VIDEO_TYPE_IDS.INDIVIDUALS.SHORTS]: (video) => {
  370. return video.querySelector('ytd-rich-grid-slim-media')?.isShort ?? false;
  371. },
  372. [VIDEO_TYPE_IDS.INDIVIDUALS.NORMAL]: (video) => {
  373. const uploadTimeNode = getUploadTimeNode(video);
  374. return uploadTimeNode ? new RegExp('^\\d+ .+ ago$').test(uploadTimeNode.innerText) : false;
  375. },
  376. [VIDEO_TYPE_IDS.INDIVIDUALS.FUNDRAISERS]: (video) => {
  377. for (const badge of getVideoBadges(video)) {
  378. if (firstWordEquals(badge, 'Fundraiser')) {
  379. return true;
  380. }
  381. }
  382. return false;
  383. },
  384. };
  385.  
  386. const CUTOFF_GETTERS = [
  387. // Watched %
  388. (video) => {
  389. const progressBar = video.querySelector('#progress');
  390. if (!progressBar) {
  391. return 0;
  392. }
  393. return Number.parseInt(progressBar.style.width.slice(0, -1));
  394. },
  395. // View count
  396. (video) => {
  397. if (isScheduled(video)) {
  398. return 0;
  399. }
  400. const {innerText} = [...getMetadataLine(video).children].find((child) => child.matches('.inline-metadata-item'));
  401. const [valueString] = innerText.split(' ');
  402. const lastChar = valueString.slice(-1);
  403. if (/\d/.test(lastChar)) {
  404. return Number.parseInt(valueString);
  405. }
  406. const valueNumber = Number.parseFloat(valueString.slice(0, -1));
  407. switch (lastChar) {
  408. case 'B':
  409. return valueNumber * 1000000000;
  410. case 'M':
  411. return valueNumber * 1000000;
  412. case 'K':
  413. return valueNumber * 1000;
  414. }
  415. return valueNumber;
  416. },
  417. // Duration (minutes)
  418. (video) => {
  419. const timeElement = video.querySelector('ytd-thumbnail-overlay-time-status-renderer');
  420. let minutes = 0;
  421. if (timeElement) {
  422. const timeParts = timeElement.innerText.split(':').map((_) => Number.parseInt(_));
  423. let timeValue = 1 / 60;
  424. for (let i = timeParts.length - 1; i >= 0; --i) {
  425. minutes += timeParts[i] * timeValue;
  426. timeValue *= 60;
  427. }
  428. }
  429. return Number.isNaN(minutes) ? 0 : minutes;
  430. },
  431. ];
  432.  
  433. const BADGE_PREDICATES = [
  434. // Verified
  435. (video) => getChannelBadges(video)
  436. .some((badge) => badge.classList.contains('badge-style-type-verified')),
  437. // Official Artist
  438. (video) => getChannelBadges(video)
  439. .some((badge) => badge.classList.contains('badge-style-type-verified-artist')),
  440. ];
  441.  
  442. // Hider functions
  443.  
  444. function loadVideo(video) {
  445. return new Promise((resolve) => {
  446. const test = () => {
  447. if (video.querySelector('#interaction.yt-icon-button')) {
  448. observer.disconnect();
  449. resolve();
  450. }
  451. };
  452. const observer = new MutationObserver(test);
  453. observer.observe(video, {
  454. childList: true,
  455. subtree: true,
  456. attributes: true,
  457. attributeOldValue: true,
  458. });
  459. test();
  460. });
  461. }
  462.  
  463. function shouldHide({filters, cutoffs, badges}, video) {
  464. for (let i = 0; i < BADGE_PREDICATES.length; ++i) {
  465. if (badges[i] !== 1 && Boolean(badges[i]) !== BADGE_PREDICATES[i](video)) {
  466. return true;
  467. }
  468. }
  469. for (let i = 0; i < CUTOFF_GETTERS.length; ++i) {
  470. const [lowerBound, upperBound] = cutoffs[i];
  471. const value = CUTOFF_GETTERS[i](video);
  472. if (value < lowerBound || value > upperBound) {
  473. return true;
  474. }
  475. }
  476. const channelName = video.querySelector('ytd-channel-name#channel-name')?.innerText;
  477. const videoName = video.querySelector('#video-title').innerText;
  478. for (const {'channels': channelRegex, 'videos': videoRegex, types} of filters) {
  479. if (
  480. (!channelName || channelRegex.test(channelName))
  481. && videoRegex.test(videoName)
  482. ) {
  483. for (const type of types) {
  484. if (VIDEO_PREDICATES[type](video)) {
  485. return true;
  486. }
  487. }
  488. }
  489. }
  490. return false;
  491. }
  492.  
  493. const hideList = (() => {
  494. const list = [];
  495. let hasReverted = true;
  496. function hide(element, doHide) {
  497. element.hidden = false;
  498. if (doHide) {
  499. element.style.display = 'none';
  500. } else {
  501. element.style.removeProperty('display');
  502. }
  503. }
  504. return {
  505. 'add'(doAct, element, doHide = true) {
  506. if (doAct) {
  507. hasReverted = false;
  508. }
  509. list.push({element, doHide, wasHidden: element.hidden});
  510. if (doAct) {
  511. hide(element, doHide);
  512. }
  513. },
  514. 'revert'(doErase) {
  515. if (!hasReverted) {
  516. hasReverted = true;
  517. for (const {element, doHide, wasHidden} of list) {
  518. hide(element, !doHide);
  519. element.hidden = wasHidden;
  520. }
  521. }
  522. if (doErase) {
  523. list.length = 0;
  524. }
  525. },
  526. 'ensure'() {
  527. if (!hasReverted) {
  528. return;
  529. }
  530. hasReverted = false;
  531. for (const {element, doHide} of list) {
  532. hide(element, doHide);
  533. }
  534. },
  535. };
  536. })();
  537.  
  538. async function hideFromRows(config, doAct, groups = getAllRows()) {
  539. for (const group of groups) {
  540. const videos = getAllVideos(group);
  541. // Process all videos in the row in parallel
  542. await Promise.all(videos.map((video) => new Promise(async (resolve) => {
  543. await loadVideo(video);
  544. if (shouldHide(config, video)) {
  545. hideList.add(doAct, video);
  546. }
  547. resolve();
  548. })));
  549. // Allow the page to update visually before moving on to the next row
  550. await new Promise((resolve) => {
  551. window.setTimeout(resolve, 0);
  552. });
  553. }
  554. }
  555.  
  556. const hideFromSections = (() => {
  557. return async (config, doAct, groups = getAllSections()) => {
  558. for (const group of groups) {
  559. const shownVideos = [];
  560. const backupVideos = [];
  561. for (const video of getAllVideos(group)) {
  562. await loadVideo(video);
  563. if (video.hidden) {
  564. if (!shouldHide(config, video)) {
  565. backupVideos.push(video);
  566. }
  567. } else {
  568. shownVideos.push(video);
  569. }
  570. }
  571. let lossCount = 0;
  572. // Process all videos in the row in parallel
  573. await Promise.all(shownVideos.map((video) => new Promise(async (resolve) => {
  574. await loadVideo(video);
  575. if (shouldHide(config, video)) {
  576. hideList.add(doAct, video);
  577. if (backupVideos.length > 0) {
  578. hideList.add(doAct, backupVideos.shift(), false);
  579. } else {
  580. lossCount++;
  581. }
  582. }
  583. resolve();
  584. })));
  585. if (lossCount >= shownVideos.length) {
  586. hideList.add(doAct, group);
  587. }
  588. // Allow the page to update visually before moving on to the next row
  589. await new Promise((resolve) => {
  590. window.setTimeout(resolve, 0);
  591. });
  592. }
  593. };
  594. })();
  595.  
  596. function hideAll(doAct = true, rows, sections, config = $config.get()) {
  597. return Promise.all([
  598. hideFromRows(config, doAct, rows),
  599. hideFromSections(config, doAct, sections),
  600. ]);
  601. }
  602.  
  603. // Helpers
  604.  
  605. function hideFromMutations(isActive, mutations) {
  606. const rows = [];
  607. const sections = [];
  608. for (const {addedNodes} of mutations) {
  609. for (const node of addedNodes) {
  610. switch (node.tagName) {
  611. case 'YTD-RICH-GRID-ROW':
  612. rows.push(node);
  613. break;
  614. case 'YTD-RICH-SECTION-RENDERER':
  615. sections.push(node);
  616. }
  617. }
  618. }
  619. hideAll(isActive(), rows, sections);
  620. }
  621.  
  622. function resetConfig(fullReset = true) {
  623. hideList.revert(fullReset);
  624. }
  625.  
  626. function getButtonDock() {
  627. return document
  628. .querySelector('ytd-browse[page-subtype="subscriptions"]')
  629. .querySelector('#contents')
  630. .querySelector('#title-container')
  631. .querySelector('#top-level-buttons-computed');
  632. }
  633.  
  634. // Button
  635.  
  636. class ClickHandler {
  637. constructor(button, onShortClick, onLongClick) {
  638. this.onShortClick = function () {
  639. onShortClick();
  640. window.clearTimeout(this.longClickTimeout);
  641. window.removeEventListener('mouseup', this.onShortClick);
  642. }.bind(this);
  643. this.onLongClick = function () {
  644. window.removeEventListener('mouseup', this.onShortClick);
  645. onLongClick();
  646. }.bind(this);
  647. this.longClickTimeout = window.setTimeout(this.onLongClick, LONG_PRESS_TIME);
  648. window.addEventListener('mouseup', this.onShortClick);
  649. }
  650. }
  651.  
  652. class Button {
  653. wasActive;
  654. isActive = false;
  655. isDormant = false;
  656. constructor() {
  657. this.element = (() => {
  658. const getSVG = () => {
  659. const svgNamespace = 'http://www.w3.org/2000/svg';
  660. const bottom = document.createElementNS(svgNamespace, 'path');
  661. 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');
  662. const top = document.createElementNS(svgNamespace, 'rect');
  663. top.setAttribute('x', '13.95');
  664. top.setAttribute('width', '294');
  665. top.setAttribute('height', '45');
  666. const g = document.createElementNS(svgNamespace, 'g');
  667. g.appendChild(bottom);
  668. g.appendChild(top);
  669. const svg = document.createElementNS(svgNamespace, 'svg');
  670. svg.setAttribute('viewBox', '-50 -50 400 400');
  671. svg.setAttribute('focusable', 'false');
  672. svg.appendChild(g);
  673. return svg;
  674. };
  675. const getNewButton = () => {
  676. const {parentElement, 'children': [, openerTemplate]} = getButtonDock();
  677. const button = openerTemplate.cloneNode(false);
  678. if (openerTemplate.innerText) {
  679. throw new Error('too early');
  680. }
  681. parentElement.appendChild(button);
  682. button.innerHTML = openerTemplate.innerHTML;
  683. button.querySelector('yt-button-shape').innerHTML = openerTemplate.querySelector('yt-button-shape').innerHTML;
  684. button.querySelector('a').removeAttribute('href');
  685. button.querySelector('yt-icon').appendChild(getSVG());
  686. button.querySelector('tp-yt-paper-tooltip').remove();
  687. return button;
  688. };
  689. return getNewButton();
  690. })();
  691. this.element.addEventListener('mousedown', this.onMouseDown.bind(this));
  692. GM.getValue(KEY_IS_ACTIVE, true).then((isActive) => {
  693. this.isActive = isActive;
  694. this.update();
  695. const videoObserver = new MutationObserver(hideFromMutations.bind(null, () => this.isActive));
  696. videoObserver.observe(
  697. document.querySelector('ytd-browse[page-subtype="subscriptions"]').querySelector('div#contents'),
  698. {childList: true},
  699. );
  700. hideAll(isActive);
  701. });
  702. let resizeCount = 0;
  703. window.addEventListener('resize', () => {
  704. const resizeId = ++resizeCount;
  705. this.forceInactive();
  706. const listener = ({detail}) => {
  707. // column size changed
  708. if (detail.actionName === 'yt-window-resized') {
  709. window.setTimeout(() => {
  710. if (resizeId !== resizeCount) {
  711. return;
  712. }
  713. this.forceInactive(false);
  714. // Don't bother re-running filters if the sub page isn't shown
  715. if (this.isDormant) {
  716. return;
  717. }
  718. resetConfig();
  719. hideAll(this.isActive);
  720. }, 1000);
  721. document.body.removeEventListener('yt-action', listener);
  722. }
  723. };
  724. document.body.addEventListener('yt-action', listener);
  725. });
  726. }
  727. forceInactive(doForce = true) {
  728. if (doForce) {
  729. // if wasActive isn't undefined, forceInactive was already called
  730. if (this.wasActive === undefined) {
  731. // Saves a GM.getValue call later
  732. this.wasActive = this.isActive;
  733. this.isActive = false;
  734. }
  735. } else {
  736. this.isActive = this.wasActive;
  737. this.wasActive = undefined;
  738. }
  739. }
  740. update() {
  741. if (this.isActive) {
  742. this.setButtonActive();
  743. }
  744. }
  745. setButtonActive() {
  746. if (this.isActive) {
  747. this.element.querySelector('svg').style.setProperty('fill', 'var(--yt-spec-call-to-action)');
  748. } else {
  749. this.element.querySelector('svg').style.setProperty('fill', 'currentcolor');
  750. }
  751. }
  752. toggleActive() {
  753. this.isActive = !this.isActive;
  754. this.setButtonActive();
  755. GM.setValue(KEY_IS_ACTIVE, this.isActive);
  756. if (this.isActive) {
  757. hideList.ensure();
  758. } else {
  759. hideList.revert(false);
  760. }
  761. }
  762. async onLongClick() {
  763. await $config.edit();
  764. resetConfig();
  765. hideAll(this.isActive);
  766. }
  767. onMouseDown(event) {
  768. if (event.button === 0) {
  769. new ClickHandler(this.element, this.toggleActive.bind(this), this.onLongClick.bind(this));
  770. }
  771. }
  772. }
  773.  
  774. // Main
  775.  
  776. (() => {
  777. let button;
  778. const loadButton = async () => {
  779. if (button) {
  780. button.isDormant = false;
  781. hideAll(button.isActive);
  782. return;
  783. }
  784. try {
  785. await $config.ready();
  786. } catch (error) {
  787. if (!$config.reset) {
  788. throw error;
  789. }
  790. if (!window.confirm(`${error.message}\n\nWould you like to erase your data?`)) {
  791. return;
  792. }
  793. $config.reset();
  794. }
  795. try {
  796. getButtonDock();
  797. button = new Button();
  798. } catch (e) {
  799. const emitter = document.getElementById('page-manager');
  800. const bound = () => {
  801. loadButton();
  802. emitter.removeEventListener('yt-action', bound);
  803. };
  804. emitter.addEventListener('yt-action', bound);
  805. }
  806. };
  807. const isGridView = () => {
  808. return Boolean(
  809. document.querySelector('ytd-browse[page-subtype="subscriptions"]:not([hidden])')
  810. && document.querySelector('ytd-browse > ytd-two-column-browse-results-renderer ytd-rich-grid-row ytd-rich-item-renderer ytd-rich-grid-media'),
  811. );
  812. };
  813. function onNavigate({detail}) {
  814. if (detail.endpoint.browseEndpoint) {
  815. const {params, browseId} = detail.endpoint.browseEndpoint;
  816. // Handle navigation to the sub feed
  817. if ((params === 'MAE%3D' || (!params && (!button || isGridView()))) && browseId === 'FEsubscriptions') {
  818. const emitter = document.querySelector('ytd-app');
  819. const event = 'yt-action';
  820. if (button || isGridView()) {
  821. loadButton();
  822. } else {
  823. const listener = ({detail}) => {
  824. if (detail.actionName === 'ytd-update-grid-state-action') {
  825. if (isGridView()) {
  826. loadButton();
  827. }
  828. emitter.removeEventListener(event, listener);
  829. }
  830. };
  831. emitter.addEventListener(event, listener);
  832. }
  833. return;
  834. }
  835. }
  836. // Handle navigation away from the sub feed
  837. if (button) {
  838. button.isDormant = true;
  839. hideList.revert();
  840. }
  841. }
  842. document.body.addEventListener('yt-navigate-finish', onNavigate);
  843. })();