YouTube Sub Feed Filter 2

Filters your YouTube subscriptions feed.

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

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