popup.js 27 KB

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