popup.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. document.addEventListener("alpine:init", () => {
  2. //TODO
  3. // - preserve playlist order (sort)
  4. // - "play/resume playlist" button (pick up where you left off)
  5. // X track timestamp to truly resume where you left off
  6. // X periodically remove watched videos
  7. // X or move to an "old" category, and add a screen to see the list
  8. // - consider separating context menu items (rather than having a sub-menu)
  9. // X view playback history (?)
  10. // - include currently open tabs in export
  11. // - support playlist management (add, remove, rename playlists)
  12. // - support input text box for adding to playlist (how to handle title?)
  13. // X option (probably a button) to add current page (url, title) to playlist
  14. // X align with addLinkToPlaylist in background.js (no repeated videos)
  15. // - button to add channel to youtube page (copy gql mutation to clipboard) (like the automa version)
  16. // - long-term: replace youtube page? rss feeds? need server?
  17. // X add personal rating feature ("enjoyed", "this was important", etc)
  18. Alpine.data("playlistManager", () => ({
  19. playlists: {},
  20. currentIndices: {},
  21. history: {},
  22. sortedHistory: [],
  23. openMenus: new Set(), // Track which menus are open
  24. currentView: 'playlists', // Track current view: 'playlists', 'history', or 'playlist'
  25. currentPlaylistName: '', // Track which playlist is being viewed
  26. playlistsForDisplay: [], // Computed array for display
  27. currentPlaylistVideos: [], // Videos for current playlist view
  28. currentTab: null, // Current active tab info
  29. isCurrentTabYoutube: false, // Whether current tab is YouTube
  30. addCurrentPageButtonText: 'Add Current Page', // Button text
  31. init() {
  32. this.loadPlaylists();
  33. this.loadHistory();
  34. this.getCurrentTab();
  35. // Add document click handler to close menus
  36. document.addEventListener('click', (e) => {
  37. // If click is not on a more button or menu, close all menus
  38. if (!e.target.closest('.more-menu-container')) {
  39. this.closeAllMenus();
  40. }
  41. });
  42. },
  43. async loadPlaylists() {
  44. try {
  45. const result = await browser.storage.local.get("playlists");
  46. console.log("LOAD RESULT", result.playlists);
  47. this.playlists = result.playlists || {};
  48. if (result.playlists) {
  49. this.currentIndices = Object.keys(result.playlists).reduce(
  50. (acc, pln) => {
  51. const ind = result.playlists[pln].findIndex(
  52. (v) => v.status !== "done",
  53. );
  54. if (ind === -1) {
  55. acc[pln] = result.playlists[pln].length;
  56. } else {
  57. acc[pln] = ind;
  58. }
  59. return acc;
  60. },
  61. {},
  62. );
  63. } else {
  64. this.currentIndices = {};
  65. }
  66. } catch (error) {
  67. console.error("Error loading playlists:", error);
  68. }
  69. this.updatePlaylistsForDisplay();
  70. },
  71. updatePlaylistsForDisplay() {
  72. this.playlistsForDisplay = Object.entries(this.playlists).map(([playlistName, videos]) => {
  73. const currentIndex = this.currentIndices[playlistName] || 0;
  74. const shouldShowTruncation = currentIndex > 0;
  75. const truncationText = shouldShowTruncation
  76. ? `(${currentIndex} previous video${currentIndex === 1 ? '' : 's'})`
  77. : '';
  78. // Get visible videos from current index onwards with original indices
  79. const visibleVideos = videos.slice(currentIndex).map((video, index) => ({
  80. ...video,
  81. originalIndex: currentIndex + index
  82. }));
  83. return {
  84. name: playlistName,
  85. videos: videos,
  86. visibleVideos: visibleVideos,
  87. shouldShowTruncation: shouldShowTruncation,
  88. truncationText: truncationText
  89. };
  90. });
  91. },
  92. updateCurrentPlaylistVideos() {
  93. if (!this.currentPlaylistName || !this.playlists[this.currentPlaylistName]) {
  94. this.currentPlaylistVideos = [];
  95. } else {
  96. this.currentPlaylistVideos = this.playlists[this.currentPlaylistName];
  97. }
  98. },
  99. async loadHistory() {
  100. try {
  101. const result = await browser.storage.local.get("history");
  102. console.log("LOAD HISTORY RESULT", result.history);
  103. this.history = result.history || {};
  104. this.sortHistoryByRecentInteraction();
  105. } catch (error) {
  106. console.error("Error loading history:", error);
  107. }
  108. },
  109. async getCurrentTab() {
  110. try {
  111. const tabs = await browser.tabs.query({ active: true, currentWindow: true });
  112. if (tabs.length > 0) {
  113. this.currentTab = tabs[0];
  114. const url = new URL(this.currentTab.url);
  115. this.isCurrentTabYoutube = url.hostname === 'www.youtube.com';
  116. this.updateAddCurrentPageButtonText();
  117. }
  118. } catch (error) {
  119. console.error("Error getting current tab:", error);
  120. this.currentTab = null;
  121. this.isCurrentTabYoutube = false;
  122. this.updateAddCurrentPageButtonText();
  123. }
  124. },
  125. updateAddCurrentPageButtonText() {
  126. if (!this.currentTab) {
  127. this.addCurrentPageButtonText = 'Unable to get current page';
  128. } else if (!this.isCurrentTabYoutube) {
  129. this.addCurrentPageButtonText = 'Add Current Page (YouTube only)';
  130. } else {
  131. this.addCurrentPageButtonText = 'Add Current Page to Playlist';
  132. }
  133. },
  134. sortHistoryByRecentInteraction() {
  135. // Convert history object to array with video ID and sort by most recent interaction
  136. this.sortedHistory = Object.entries(this.history)
  137. .map(([videoId, videoData]) => {
  138. const lastInteraction = videoData.history.length > 0
  139. ? Math.max(...videoData.history.map(event => event.timestamp))
  140. : 0;
  141. // Pre-process events with formatted data for CSP compliance
  142. const processedEvents = videoData.history
  143. .slice()
  144. .reverse()
  145. .map((event, index) => ({
  146. ...event,
  147. formattedAction: this.formatActionName(event.action),
  148. formattedPosition: `at ${this.formatVideoPosition(event.position)}`,
  149. formattedTimestamp: this.formatTimestamp(event.timestamp),
  150. uniqueKey: `${videoId}-${event.timestamp}-${index}`
  151. }));
  152. return {
  153. videoId,
  154. formattedVideoId: `(${videoId})`,
  155. ...videoData,
  156. lastInteraction,
  157. processedEvents,
  158. tags: videoData.tags || [] // Ensure tags array exists
  159. };
  160. })
  161. .sort((a, b) => b.lastInteraction - a.lastInteraction);
  162. },
  163. formatTimestamp(timestamp) {
  164. const date = new Date(timestamp);
  165. const now = new Date();
  166. const diffMs = now - date;
  167. const diffMins = Math.floor(diffMs / (1000 * 60));
  168. const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  169. const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  170. if (diffMins < 1) return 'Just now';
  171. if (diffMins < 60) return `${diffMins} minute${diffMins > 1 ? 's' : ''} ago`;
  172. if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
  173. if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
  174. return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
  175. },
  176. formatVideoPosition(seconds) {
  177. const minutes = Math.floor(seconds / 60);
  178. const remainingSeconds = Math.floor(seconds % 60);
  179. return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  180. },
  181. async toggleTag(videoId, tag) {
  182. // Create a deep copy of history to avoid proxy issues
  183. const history = JSON.parse(JSON.stringify(this.history));
  184. if (!history[videoId]) {
  185. console.error(`Video ${videoId} not found in history`);
  186. return;
  187. }
  188. const videoData = history[videoId];
  189. if (!videoData.tags) {
  190. videoData.tags = [];
  191. }
  192. const tagIndex = videoData.tags.indexOf(tag);
  193. if (tagIndex === -1) {
  194. // Add tag
  195. videoData.tags.push(tag);
  196. } else {
  197. // Remove tag
  198. videoData.tags.splice(tagIndex, 1);
  199. }
  200. // Save to storage and update local state
  201. try {
  202. await browser.storage.local.set({ history: history });
  203. this.history = history;
  204. this.sortHistoryByRecentInteraction(); // Refresh display
  205. } catch (error) {
  206. console.error("Error saving tag changes:", error);
  207. }
  208. },
  209. isTagActive(videoId, tag) {
  210. const videoData = this.history[videoId];
  211. return videoData && videoData.tags && videoData.tags.includes(tag);
  212. },
  213. formatActionName(action) {
  214. const actionMap = {
  215. 'play': 'Started',
  216. 'playing': 'Playing',
  217. 'pause': 'Paused',
  218. 'ended': 'Finished'
  219. };
  220. return actionMap[action] || action;
  221. },
  222. formatPlaylistName(name) {
  223. // Convert "listening-1" to "Listening - 1"
  224. return name
  225. .split("-")
  226. .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
  227. .join(" - ");
  228. },
  229. openVideo(url) {
  230. browser.tabs.create({ url });
  231. },
  232. async removeVideo(playlistName, index) {
  233. const playlists = JSON.parse(JSON.stringify(this.playlists));
  234. // Make a copy of the current playlist
  235. const playlist = [...playlists[playlistName]];
  236. // Remove the video at the specified index
  237. playlist.splice(index, 1);
  238. // Create an updated playlists object with the remaining playlists unchanged
  239. const updatedPlaylists = {
  240. ...playlists,
  241. [playlistName]: playlist,
  242. };
  243. // Update the playlists in storage
  244. try {
  245. await browser.storage.local.set({ playlists: updatedPlaylists });
  246. this.playlists = updatedPlaylists;
  247. this.updatePlaylistsForDisplay();
  248. this.updateCurrentPlaylistVideos();
  249. } catch (error) {
  250. console.error("Error removing video:", error);
  251. }
  252. },
  253. async moveVideoUp(playlistName, index) {
  254. // Can't move the first item up
  255. if (index <= 0) return;
  256. const playlists = JSON.parse(JSON.stringify(this.playlists));
  257. // Make a copy of the current playlist
  258. const playlist = [...playlists[playlistName]];
  259. // Swap the video with the one above it
  260. [playlist[index], playlist[index - 1]] = [
  261. playlist[index - 1],
  262. playlist[index],
  263. ];
  264. // Create an updated playlists object
  265. const updatedPlaylists = {
  266. ...playlists,
  267. [playlistName]: playlist,
  268. };
  269. // Update the playlists in storage
  270. try {
  271. await browser.storage.local.set({ playlists: updatedPlaylists });
  272. this.playlists = updatedPlaylists;
  273. this.updatePlaylistsForDisplay();
  274. this.updateCurrentPlaylistVideos();
  275. } catch (error) {
  276. console.error("Error moving video up:", error);
  277. }
  278. },
  279. async moveVideoDown(playlistName, index) {
  280. const playlists = JSON.parse(JSON.stringify(this.playlists));
  281. const playlist = [...playlists[playlistName]];
  282. // Can't move the last item down
  283. if (index >= playlist.length - 1) return;
  284. // Swap the video with the one below it
  285. [playlist[index], playlist[index + 1]] = [
  286. playlist[index + 1],
  287. playlist[index],
  288. ];
  289. // Create an updated playlists object
  290. const updatedPlaylists = {
  291. ...playlists,
  292. [playlistName]: playlist,
  293. };
  294. // Update the playlists in storage
  295. try {
  296. await browser.storage.local.set({ playlists: updatedPlaylists });
  297. this.playlists = updatedPlaylists;
  298. this.updatePlaylistsForDisplay();
  299. this.updateCurrentPlaylistVideos();
  300. } catch (error) {
  301. console.error("Error moving video down:", error);
  302. }
  303. },
  304. async addCurrentPageToPlaylist() {
  305. if (!this.currentTab || !this.isCurrentTabYoutube || !this.currentPlaylistName) {
  306. return;
  307. }
  308. // Create video object using current tab info
  309. const video = {
  310. url: this.currentTab.url,
  311. title: this.currentTab.title,
  312. status: "new"
  313. };
  314. // Use shared utility function to add video (handles duplicate checking)
  315. const wasAdded = await PlaylistUtils.addVideoToPlaylist(this.currentPlaylistName, video);
  316. if (wasAdded) {
  317. // Refresh displays only if video was actually added
  318. this.loadPlaylists(); // This will update both display arrays
  319. } else {
  320. // Could show user feedback that video already exists
  321. console.log("Video already exists in a playlist");
  322. }
  323. },
  324. async exportPlaylists() {
  325. try {
  326. // Get current playlists
  327. const playlistResult = await browser.storage.local.get("playlists");
  328. const playlists = playlistResult.playlists || {};
  329. // Get playback history
  330. const historyResult = await browser.storage.local.get("history");
  331. const playbackHistory = historyResult.history || {};
  332. // Create export data object
  333. const exportData = {
  334. playlists,
  335. playbackHistory,
  336. exportDate: new Date().toISOString(),
  337. };
  338. // Convert to JSON
  339. const jsonString = JSON.stringify(exportData, null, 2);
  340. // Create download
  341. const blob = new Blob([jsonString], { type: "application/json" });
  342. const url = URL.createObjectURL(blob);
  343. // Trigger download
  344. const a = document.createElement("a");
  345. a.href = url;
  346. a.download = `playlists-export-${new Date().toISOString().split("T")[0]}.json`;
  347. document.body.appendChild(a);
  348. a.click();
  349. // Clean up
  350. setTimeout(() => {
  351. document.body.removeChild(a);
  352. URL.revokeObjectURL(url);
  353. }, 100);
  354. } catch (error) {
  355. console.error("Error exporting playlists:", error);
  356. }
  357. },
  358. videotitle: {
  359. ["@click"]() {
  360. console.log("TITLE CLICK", this.$el);
  361. },
  362. },
  363. videoPlayLink: {
  364. ["@click.prevent"]() {
  365. browser.tabs.update({ url: this.$el.href });
  366. },
  367. },
  368. isCurrentVideo(playlistName, index) {
  369. const currentIndex = this.currentIndices[playlistName];
  370. return currentIndex === index;
  371. },
  372. isDoneVideo(playlistName, index) {
  373. const currentIndex = this.currentIndices[playlistName];
  374. return index < currentIndex;
  375. },
  376. videoItemClass: {
  377. [":class"]() {
  378. const playlistName = this.$el.dataset.playlistName;
  379. const index = parseInt(this.$el.dataset.playlistIndex);
  380. const video = this.playlists[playlistName][index];
  381. return {
  382. "current-video": this.isCurrentVideo(playlistName, index),
  383. "done-video":
  384. this.isDoneVideo(playlistName, index) && video.status === "done",
  385. };
  386. },
  387. },
  388. removeVideoButton: {
  389. ["@click"]() {
  390. this.removeVideo(
  391. this.$el.dataset.playlistName,
  392. this.$el.dataset.playlistIndex,
  393. );
  394. this.closeAllMenus();
  395. },
  396. },
  397. moveUpButton: {
  398. ["@click"]() {
  399. this.moveVideoUp(
  400. this.$el.dataset.playlistName,
  401. parseInt(this.$el.dataset.playlistIndex),
  402. );
  403. },
  404. [":disabled"]() {
  405. return parseInt(this.$el.dataset.playlistIndex) === 0;
  406. },
  407. },
  408. moveDownButton: {
  409. ["@click"]() {
  410. this.moveVideoDown(
  411. this.$el.dataset.playlistName,
  412. parseInt(this.$el.dataset.playlistIndex),
  413. );
  414. },
  415. [":disabled"]() {
  416. return (
  417. parseInt(this.$el.dataset.playlistIndex) ===
  418. this.playlists[this.$el.dataset.playlistName].length - 1
  419. );
  420. },
  421. },
  422. exportButton: {
  423. ["@click"]() {
  424. this.exportPlaylists();
  425. },
  426. },
  427. importButton: {
  428. ["@click"]() {
  429. document.getElementById("import-file-input").click();
  430. },
  431. },
  432. importFileInput: {
  433. ["@change"]() {
  434. this.importFile(this.$event);
  435. },
  436. },
  437. importFile(event) {
  438. const file = event.target.files[0];
  439. if (!file) return;
  440. const reader = new FileReader();
  441. reader.onload = (e) => {
  442. try {
  443. const importedData = JSON.parse(e.target.result);
  444. this.validateAndImportPlaylists(importedData);
  445. } catch (error) {
  446. console.error("Error parsing JSON file:", error);
  447. alert(
  448. "Invalid JSON file. Please select a valid playlist export file.",
  449. );
  450. } finally {
  451. // Reset the file input so the same file can be selected again
  452. event.target.value = "";
  453. }
  454. };
  455. reader.readAsText(file);
  456. },
  457. validateAndImportPlaylists(data) {
  458. // Validate the playlists structure
  459. if (!data.playlists || typeof data.playlists !== "object") {
  460. alert("Invalid file format: Missing or invalid 'playlists' property");
  461. return;
  462. }
  463. // Validate each playlist
  464. const validPlaylists = {};
  465. let hasErrors = false;
  466. for (const [playlistName, videos] of Object.entries(data.playlists)) {
  467. // Check if videos is an array
  468. if (!Array.isArray(videos)) {
  469. console.error(
  470. `Playlist '${playlistName}' does not contain a valid array of videos`,
  471. );
  472. hasErrors = true;
  473. continue;
  474. }
  475. // Validate each video in the playlist
  476. const validVideos = videos.filter((video) => {
  477. if (!video || typeof video !== "object") {
  478. console.error(`Invalid video object in '${playlistName}'`);
  479. return false;
  480. }
  481. if (
  482. !video.url ||
  483. typeof video.url !== "string" ||
  484. !video.title ||
  485. typeof video.title !== "string"
  486. ) {
  487. console.error(
  488. `Video in '${playlistName}' missing required properties (url, title)`,
  489. );
  490. return false;
  491. }
  492. return true;
  493. });
  494. // Add the validated playlist if it has valid videos
  495. if (validVideos.length > 0) {
  496. validPlaylists[playlistName] = validVideos;
  497. }
  498. }
  499. if (Object.keys(validPlaylists).length === 0) {
  500. alert("No valid playlists found in the import file");
  501. return;
  502. }
  503. if (hasErrors) {
  504. const confirmImport = confirm(
  505. "Some playlists or videos were invalid and will be skipped. Do you want to continue with the import?",
  506. );
  507. if (!confirmImport) return;
  508. }
  509. // Update storage and state
  510. this.updatePlaylists(validPlaylists);
  511. },
  512. async updatePlaylists(playlists) {
  513. try {
  514. await browser.storage.local.set({ playlists });
  515. this.playlists = playlists;
  516. this.updatePlaylistsForDisplay();
  517. this.updateCurrentPlaylistVideos();
  518. alert("Playlists imported successfully!");
  519. } catch (error) {
  520. console.error("Error updating playlists:", error);
  521. alert("Error importing playlists: " + error.message);
  522. }
  523. },
  524. getMenuId(playlistName, index) {
  525. return `${playlistName}-${index}`;
  526. },
  527. isMenuOpen(playlistName, index) {
  528. return this.openMenus.has(this.getMenuId(playlistName, index));
  529. },
  530. toggleMenu(playlistName, index) {
  531. const menuId = this.getMenuId(playlistName, index);
  532. if (this.openMenus.has(menuId)) {
  533. this.openMenus.delete(menuId);
  534. } else {
  535. // Close all other menus first
  536. this.openMenus.clear();
  537. this.openMenus.add(menuId);
  538. }
  539. },
  540. closeAllMenus() {
  541. this.openMenus.clear();
  542. },
  543. moreMenuButton: {
  544. ["@click.stop"]() {
  545. this.toggleMenu(
  546. this.$el.dataset.playlistName,
  547. parseInt(this.$el.dataset.playlistIndex)
  548. );
  549. },
  550. },
  551. moreMenu: {
  552. ["x-show"]() {
  553. return this.isMenuOpen(
  554. this.$el.dataset.playlistName,
  555. parseInt(this.$el.dataset.playlistIndex)
  556. );
  557. },
  558. },
  559. // View navigation methods
  560. showHistory() {
  561. this.currentView = 'history';
  562. this.loadHistory(); // Refresh history data when switching to history view
  563. },
  564. showPlaylists() {
  565. this.currentView = 'playlists';
  566. },
  567. showPlaylist(playlistName) {
  568. this.currentView = 'playlist';
  569. this.currentPlaylistName = playlistName;
  570. this.updateCurrentPlaylistVideos();
  571. },
  572. // Methods for truncated display
  573. shouldShowTruncation(playlistName) {
  574. const currentIndex = this.currentIndices[playlistName] || 0;
  575. return currentIndex > 0;
  576. },
  577. getTruncationText(playlistName) {
  578. const currentIndex = this.currentIndices[playlistName] || 0;
  579. const count = currentIndex;
  580. return `(${count} previous video${count === 1 ? '' : 's'})`;
  581. },
  582. getVisibleVideos(playlistName, videos) {
  583. const currentIndex = this.currentIndices[playlistName] || 0;
  584. // Show from current video onwards, but keep original indices
  585. return videos.slice(currentIndex).map((video, index) => ({
  586. ...video,
  587. originalIndex: currentIndex + index
  588. }));
  589. },
  590. getCurrentPlaylistVideos() {
  591. if (!this.currentPlaylistName || !this.playlists[this.currentPlaylistName]) {
  592. return [];
  593. }
  594. return this.playlists[this.currentPlaylistName];
  595. },
  596. // Button bindings for navigation
  597. historyButton: {
  598. ["@click"]() {
  599. this.showHistory();
  600. },
  601. },
  602. backButton: {
  603. ["@click"]() {
  604. this.showPlaylists();
  605. },
  606. },
  607. // Event handlers for playlist navigation
  608. playlistNameClick: {
  609. ["@click"]() {
  610. const playlistName = this.$el.dataset.playlistName;
  611. this.showPlaylist(playlistName);
  612. },
  613. },
  614. truncatedVideosClick: {
  615. ["@click"]() {
  616. const playlistName = this.$el.dataset.playlistName;
  617. this.showPlaylist(playlistName);
  618. },
  619. },
  620. truncatedVideosClick: {
  621. ["@click"]() {
  622. const playlistName = this.$el.dataset.playlistName;
  623. this.showPlaylist(playlistName);
  624. },
  625. },
  626. truncatedVideosDisplay: {
  627. ["x-show"]() {
  628. const playlistName = this.$el.dataset.playlistName;
  629. const playlistData = this.playlistsForDisplay.find(p => p.name === playlistName);
  630. return playlistData ? playlistData.shouldShowTruncation : false;
  631. },
  632. ["@click"]() {
  633. const playlistName = this.$el.dataset.playlistName;
  634. this.showPlaylist(playlistName);
  635. },
  636. },
  637. // CSP-compliant view bindings
  638. playlistsHeader: {
  639. ["x-show"]() {
  640. return this.currentView === 'playlists';
  641. },
  642. },
  643. historyHeader: {
  644. ["x-show"]() {
  645. return this.currentView === 'history';
  646. },
  647. },
  648. playlistViewHeader: {
  649. ["x-show"]() {
  650. return this.currentView === 'playlist';
  651. },
  652. },
  653. playlistsContainer: {
  654. ["x-show"]() {
  655. return this.currentView === 'playlists';
  656. },
  657. },
  658. historyContainer: {
  659. ["x-show"]() {
  660. return this.currentView === 'history';
  661. },
  662. },
  663. playlistViewContainer: {
  664. ["x-show"]() {
  665. return this.currentView === 'playlist';
  666. },
  667. },
  668. exportContainer: {
  669. ["x-show"]() {
  670. return this.currentView === 'playlists';
  671. },
  672. },
  673. // History-specific bindings for CSP compliance
  674. historyEmptyState: {
  675. ["x-show"]() {
  676. return this.sortedHistory.length === 0;
  677. },
  678. },
  679. // Playlist view-specific bindings for CSP compliance
  680. playlistViewEmptyState: {
  681. ["x-show"]() {
  682. return this.currentPlaylistVideos.length === 0;
  683. },
  684. },
  685. // Tag chip bindings for CSP compliance
  686. tagChip: {
  687. ["@click"]() {
  688. const videoId = this.$el.dataset.videoId;
  689. const tag = this.$el.dataset.tag;
  690. this.toggleTag(videoId, tag);
  691. },
  692. [":class"]() {
  693. const videoId = this.$el.dataset.videoId;
  694. const tag = this.$el.dataset.tag;
  695. return {
  696. 'active': this.isTagActive(videoId, tag)
  697. };
  698. },
  699. },
  700. // Add current page button binding
  701. addCurrentPageButton: {
  702. ["@click"]() {
  703. this.addCurrentPageToPlaylist();
  704. },
  705. [":disabled"]() {
  706. return !this.currentTab || !this.isCurrentTabYoutube || !this.currentPlaylistName;
  707. },
  708. [":class"]() {
  709. return {
  710. 'disabled': !this.currentTab || !this.isCurrentTabYoutube || !this.currentPlaylistName
  711. };
  712. },
  713. },
  714. }));
  715. });