Youtube Save To Playlist Hotkey And Filter

Adds a P hotkey to Youtube, to bring up the Save to Playlist dialog. Playlists will be displayed alfabetically sorted, any any playlist the current video belongs to, will be shown at the top. Also adds a focuced filter input field. If nothing is written into the filter input, all playlists will be shown, alternatively only the playlists where the name containes the sequence of letters typed in the input field, will be displayed. Press escape to exit the dialog.

当前为 2025-01-01 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Youtube Save To Playlist Hotkey And Filter
  3. // @namespace https://gist.github.com/f-steff
  4. // @version 1.1
  5. // @description Adds a P hotkey to Youtube, to bring up the Save to Playlist dialog. Playlists will be displayed alfabetically sorted, any any playlist the current video belongs to, will be shown at the top. Also adds a focuced filter input field. If nothing is written into the filter input, all playlists will be shown, alternatively only the playlists where the name containes the sequence of letters typed in the input field, will be displayed. Press escape to exit the dialog.
  6. // @author Flemming Steffensen
  7. // @license MIT
  8. // @match http://www.youtube.com/*
  9. // @match https://www.youtube.com/*
  10. // @include http://www.youtube.com/*
  11. // @include https://www.youtube.com/*
  12. // @grant none
  13. // @homepageURL https://gist.github.com/f-steff/4d765eef037e9b751c58d43490ebad62
  14. // @run-at document-start
  15. // ==/UserScript==
  16.  
  17. (function (d) {
  18.  
  19. /**
  20. * Pressing 'p' simulates a click on YouTube's "Save" button to open the dialog.
  21. */
  22. function openSaveToPlaylistDialog() {
  23. // Commonly, there's a button with aria-label="Save" or aria-label^="Save"
  24. // near the Like/Dislike/Share row on the watch page.
  25. const saveButton = d.querySelector('button[aria-label^="Save"]');
  26. if (saveButton) {
  27. saveButton.click();
  28. } else {
  29. console.log("Could not find 'Save' button. Adjust the selector if needed.");
  30. }
  31. }
  32.  
  33. // Listen for the 'p' key at the document level
  34. d.addEventListener('keydown', evt => {
  35. // Avoid capturing if user holds Ctrl/Alt/Meta, or if in a text field, etc.
  36. if (evt.key === 'p' && !evt.ctrlKey && !evt.altKey && !evt.metaKey) {
  37. // Prevent YouTube from interpreting 'p' in any other way
  38. evt.preventDefault();
  39. evt.stopPropagation();
  40.  
  41. // Attempt to open the "Save to playlist" dialog
  42. openSaveToPlaylistDialog();
  43. }
  44. }, true);
  45.  
  46. /**
  47. * Sort playlists such that:
  48. * - checked items (aria-checked="true") come first,
  49. * - then everything else in alphabetical (0-9,A→Z).
  50. */
  51. function sortPlaylist(playlist) {
  52. let options = query(playlist, 'ytd-playlist-add-to-option-renderer');
  53. let optionsMap = new Map();
  54.  
  55. // Collect items by playlist title
  56. options.forEach(op => {
  57. let formattedString = query(op, 'yt-formatted-string')[0];
  58. let title = formattedString?.getAttribute('title') || '';
  59. if (!optionsMap.has(title)) {
  60. optionsMap.set(title, []);
  61. }
  62. optionsMap.get(title).push(op);
  63. });
  64.  
  65. // Sort so "checked" groups come first, then A→Z
  66. let sortedEntries = [...optionsMap.entries()].sort(([titleA, groupA], [titleB, groupB]) => {
  67. const checkedA = groupA.some(
  68. op => query(op, 'tp-yt-paper-checkbox[aria-checked="true"]').length
  69. );
  70. const checkedB = groupB.some(
  71. op => query(op, 'tp-yt-paper-checkbox[aria-checked="true"]').length
  72. );
  73.  
  74. if (checkedA && !checkedB) return -1;
  75. if (checkedB && !checkedA) return 1;
  76.  
  77. // Otherwise alphabetical
  78. const upA = titleA.toUpperCase();
  79. const upB = titleB.toUpperCase();
  80. if (upA < upB) return -1;
  81. if (upA > upB) return 1;
  82. return 0;
  83. });
  84.  
  85. // Re-insert items in sorted order
  86. for (const [, group] of sortedEntries) {
  87. for (const opNode of group) {
  88. playlist.appendChild(opNode);
  89. }
  90. }
  91. }
  92.  
  93. /**
  94. * Filter all playlist entries based on user-typed substring.
  95. * If the filter is blank, show everything; otherwise hide non-matches.
  96. */
  97. function filterPlaylist(playlist, filterText) {
  98. let options = query(playlist, 'ytd-playlist-add-to-option-renderer');
  99. const text = filterText.trim().toLowerCase();
  100.  
  101. options.forEach(op => {
  102. let formattedString = query(op, 'yt-formatted-string')[0];
  103. let title = (formattedString?.getAttribute('title') || '').toLowerCase();
  104. op.style.display = (text && !title.includes(text)) ? 'none' : 'block';
  105. });
  106. }
  107.  
  108. /**
  109. * When the dialog closes, re-attach the observer so we see the next open event.
  110. */
  111. function observePaperDialogClose(paperDialog, onCloseDialog) {
  112. let ob = new MutationObserver((mutations, me) => {
  113. mutations.forEach(mutation => {
  114. if (mutation.type === 'attributes' && mutation.attributeName === 'aria-hidden') {
  115. me.disconnect();
  116. onCloseDialog();
  117. }
  118. });
  119. });
  120. ob.observe(paperDialog, { attributes: true });
  121. }
  122.  
  123. /**
  124. * Main logic: watch for the "Add to Playlist" dialog, then
  125. * Insert input, sort once, filter, focus the input, etc.
  126. * Added a small setTimeout to avoid first-time invocation timing issues.
  127. */
  128. function handlePopupContainer(popupContainer) {
  129. let currentFilter = '';
  130. const popupObserverConfig = { subtree: true, childList: true };
  131.  
  132. const popupContainerObserver = new MutationObserver(function (mut, me) {
  133. // Defer so the DOM has time to settle on first invocation
  134. setTimeout(() => {
  135. const paperDialog = query(popupContainer, 'tp-yt-paper-dialog')[0];
  136. if (paperDialog) {
  137. // Sort/insert only once per open
  138. me.disconnect();
  139.  
  140. // Re-attach after closing
  141. observePaperDialogClose(paperDialog, function () {
  142. popupContainerObserver.observe(popupContainer, popupObserverConfig);
  143. });
  144.  
  145. // Look for "Save video to..."
  146. const headingSpan = query(
  147. paperDialog,
  148. 'span.yt-core-attributed-string[role="text"]'
  149. ).find(el => el.textContent.trim() === 'Save video to...');
  150.  
  151. // Grab #playlists container
  152. const playlistContainer = query(paperDialog, '#playlists')[0];
  153.  
  154. if (headingSpan && playlistContainer) {
  155. // If we haven't inserted our input yet, do it now
  156. const existingFilterInput = d.getElementById('filterText');
  157. if (!existingFilterInput) {
  158. // Create <input> and <br>
  159. const filterInput = d.createElement('input');
  160. filterInput.id = 'filterText';
  161. filterInput.type = 'text';
  162. filterInput.placeholder = 'Filter';
  163.  
  164. const br = d.createElement('br');
  165.  
  166. headingSpan.parentNode.appendChild(filterInput);
  167. headingSpan.parentNode.appendChild(br);
  168.  
  169. // On typing => filter
  170. filterInput.addEventListener('input', evt => {
  171. currentFilter = evt.target.value;
  172. filterPlaylist(playlistContainer, currentFilter);
  173. });
  174. }
  175.  
  176. // Sort once for this session
  177. sortPlaylist(playlistContainer);
  178.  
  179. // Re-apply current filter (if any)
  180. filterPlaylist(playlistContainer, currentFilter);
  181.  
  182. // Focus
  183. const input = d.getElementById('filterText');
  184. if (input) {
  185. input.focus();
  186. }
  187. }
  188. }
  189. }, 10); // 10ms delay
  190. });
  191.  
  192. // Start observing
  193. popupContainerObserver.observe(popupContainer, popupObserverConfig);
  194. }
  195.  
  196. /**
  197. * A top-level observer that waits for <ytd-popup-container> to show up,
  198. * then calls handlePopupContainer() exactly once.
  199. */
  200. const documentObserver = new MutationObserver(function (mutations, me) {
  201. const popupContainer = query(d, 'ytd-popup-container')[0];
  202. if (popupContainer) {
  203. console.log("Found ytd-popup-container");
  204. handlePopupContainer(popupContainer);
  205. me.disconnect(); // stop once found
  206. }
  207. });
  208. documentObserver.observe(d, { childList: true, subtree: true });
  209.  
  210. /**
  211. * Helper: safely do querySelectorAll, returns an Array
  212. */
  213. function query(startNode, selector) {
  214. try {
  215. return Array.prototype.slice.call(startNode.querySelectorAll(selector));
  216. } catch (e) {
  217. return [];
  218. }
  219. }
  220.  
  221. })(document);