popup.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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. // X 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. // Get open tabs
  393. let openTabs = [];
  394. try {
  395. const tabsResult = await browser.tabs.query({});
  396. openTabs = tabsResult
  397. .filter(tab => tab.url &&
  398. !tab.url.startsWith('moz-extension://') &&
  399. !tab.url.startsWith('about:') &&
  400. !tab.url.startsWith('chrome://'))
  401. .map(tab => ({
  402. url: tab.url,
  403. title: tab.title || 'Untitled'
  404. }));
  405. } catch (error) {
  406. console.warn("Could not retrieve open tabs:", error);
  407. openTabs = [];
  408. }
  409. // Create export data object
  410. const exportData = {
  411. playlists,
  412. playbackHistory,
  413. openTabs,
  414. exportDate: new Date().toISOString(),
  415. };
  416. // Convert to JSON
  417. const jsonString = JSON.stringify(exportData, null, 2);
  418. // Create download
  419. const blob = new Blob([jsonString], { type: "application/json" });
  420. const url = URL.createObjectURL(blob);
  421. // Trigger download
  422. const a = document.createElement("a");
  423. a.href = url;
  424. a.download = `playlists-export-${new Date().toISOString().split("T")[0]}.json`;
  425. document.body.appendChild(a);
  426. a.click();
  427. // Clean up
  428. setTimeout(() => {
  429. document.body.removeChild(a);
  430. URL.revokeObjectURL(url);
  431. }, 100);
  432. } catch (error) {
  433. console.error("Error exporting playlists:", error);
  434. }
  435. },
  436. videotitle: {
  437. ["@click"]() {
  438. console.log("TITLE CLICK", this.$el);
  439. },
  440. },
  441. videoPlayLink: {
  442. ["@click.prevent"]() {
  443. browser.tabs.update({ url: this.$el.href });
  444. },
  445. },
  446. isNonContiguousDone(playlistName, videoIndex) {
  447. const playlist = this.playlists[playlistName];
  448. if (!playlist || !playlist[videoIndex] || playlist[videoIndex].status !== "done") {
  449. return false;
  450. }
  451. // Check if there's any non-done video before this done video
  452. for (let i = 0; i < videoIndex; i++) {
  453. if (playlist[i].status !== "done") {
  454. return true;
  455. }
  456. }
  457. return false;
  458. },
  459. isCurrentVideo(playlistName, index) {
  460. const currentIndex = this.currentIndices[playlistName];
  461. return currentIndex === index;
  462. },
  463. isDoneVideo(playlistName, index) {
  464. const currentIndex = this.currentIndices[playlistName];
  465. return index < currentIndex;
  466. },
  467. isVideoDone(playlistName, index) {
  468. const video = this.playlists[playlistName] && this.playlists[playlistName][index];
  469. return video && video.status === "done";
  470. },
  471. videoItemClass: {
  472. [":class"]() {
  473. const playlistName = this.$el.dataset.playlistName;
  474. const index = parseInt(this.$el.dataset.playlistIndex);
  475. const video = this.playlists[playlistName][index];
  476. return {
  477. "current-video": this.isCurrentVideo(playlistName, index),
  478. "done-video":
  479. this.isDoneVideo(playlistName, index) && video.status === "done",
  480. "non-contiguous-done-video": this.isNonContiguousDone(playlistName, index),
  481. };
  482. },
  483. },
  484. removeVideoButton: {
  485. ["@click"]() {
  486. this.removeVideo(
  487. this.$el.dataset.playlistName,
  488. this.$el.dataset.playlistIndex,
  489. );
  490. this.closeAllMenus();
  491. },
  492. },
  493. toggleVideoDoneButton: {
  494. ["@click"]() {
  495. this.toggleVideoDoneStatus(
  496. this.$el.dataset.playlistName,
  497. parseInt(this.$el.dataset.playlistIndex),
  498. );
  499. this.closeAllMenus();
  500. },
  501. },
  502. moveUpButton: {
  503. ["@click"]() {
  504. this.moveVideoUp(
  505. this.$el.dataset.playlistName,
  506. parseInt(this.$el.dataset.playlistIndex),
  507. );
  508. },
  509. [":disabled"]() {
  510. return parseInt(this.$el.dataset.playlistIndex) === 0;
  511. },
  512. },
  513. moveDownButton: {
  514. ["@click"]() {
  515. this.moveVideoDown(
  516. this.$el.dataset.playlistName,
  517. parseInt(this.$el.dataset.playlistIndex),
  518. );
  519. },
  520. [":disabled"]() {
  521. return (
  522. parseInt(this.$el.dataset.playlistIndex) ===
  523. this.playlists[this.$el.dataset.playlistName].length - 1
  524. );
  525. },
  526. },
  527. exportButton: {
  528. ["@click"]() {
  529. this.exportPlaylists();
  530. },
  531. },
  532. importButton: {
  533. ["@click"]() {
  534. document.getElementById("import-file-input").click();
  535. },
  536. },
  537. importFileInput: {
  538. ["@change"]() {
  539. this.importFile(this.$event);
  540. },
  541. },
  542. importFile(event) {
  543. const file = event.target.files[0];
  544. if (!file) return;
  545. const reader = new FileReader();
  546. reader.onload = (e) => {
  547. try {
  548. const importedData = JSON.parse(e.target.result);
  549. this.validateAndImportPlaylists(importedData);
  550. } catch (error) {
  551. console.error("Error parsing JSON file:", error);
  552. alert(
  553. "Invalid JSON file. Please select a valid playlist export file.",
  554. );
  555. } finally {
  556. // Reset the file input so the same file can be selected again
  557. event.target.value = "";
  558. }
  559. };
  560. reader.readAsText(file);
  561. },
  562. validateAndImportPlaylists(data) {
  563. // Validate the playlists structure
  564. if (!data.playlists || typeof data.playlists !== "object") {
  565. alert("Invalid file format: Missing or invalid 'playlists' property");
  566. return;
  567. }
  568. // Validate each playlist
  569. const validPlaylists = {};
  570. let hasErrors = false;
  571. for (const [playlistName, videos] of Object.entries(data.playlists)) {
  572. // Check if videos is an array
  573. if (!Array.isArray(videos)) {
  574. console.error(
  575. `Playlist '${playlistName}' does not contain a valid array of videos`,
  576. );
  577. hasErrors = true;
  578. continue;
  579. }
  580. // Validate each video in the playlist
  581. const validVideos = videos.filter((video) => {
  582. if (!video || typeof video !== "object") {
  583. console.error(`Invalid video object in '${playlistName}'`);
  584. return false;
  585. }
  586. if (
  587. !video.url ||
  588. typeof video.url !== "string" ||
  589. !video.title ||
  590. typeof video.title !== "string"
  591. ) {
  592. console.error(
  593. `Video in '${playlistName}' missing required properties (url, title)`,
  594. );
  595. return false;
  596. }
  597. return true;
  598. });
  599. // Add the validated playlist if it has valid videos
  600. if (validVideos.length > 0) {
  601. validPlaylists[playlistName] = validVideos;
  602. }
  603. }
  604. if (Object.keys(validPlaylists).length === 0) {
  605. alert("No valid playlists found in the import file");
  606. return;
  607. }
  608. if (hasErrors) {
  609. const confirmImport = confirm(
  610. "Some playlists or videos were invalid and will be skipped. Do you want to continue with the import?",
  611. );
  612. if (!confirmImport) return;
  613. }
  614. // Update storage and state
  615. this.updatePlaylists(validPlaylists);
  616. },
  617. async updatePlaylists(playlists) {
  618. try {
  619. await browser.storage.local.set({ playlists });
  620. this.playlists = playlists;
  621. this.updatePlaylistsForDisplay();
  622. this.updateCurrentPlaylistVideos();
  623. alert("Playlists imported successfully!");
  624. } catch (error) {
  625. console.error("Error updating playlists:", error);
  626. alert("Error importing playlists: " + error.message);
  627. }
  628. },
  629. getMenuId(playlistName, index) {
  630. return `${playlistName}-${index}`;
  631. },
  632. isMenuOpen(playlistName, index) {
  633. return this.openMenus.has(this.getMenuId(playlistName, index));
  634. },
  635. toggleMenu(playlistName, index) {
  636. const menuId = this.getMenuId(playlistName, index);
  637. if (this.openMenus.has(menuId)) {
  638. this.openMenus.delete(menuId);
  639. } else {
  640. // Close all other menus first
  641. this.openMenus.clear();
  642. this.openMenus.add(menuId);
  643. }
  644. },
  645. closeAllMenus() {
  646. this.openMenus.clear();
  647. },
  648. moreMenuButton: {
  649. ["@click.stop"]() {
  650. this.toggleMenu(
  651. this.$el.dataset.playlistName,
  652. parseInt(this.$el.dataset.playlistIndex),
  653. );
  654. },
  655. },
  656. moreMenu: {
  657. ["x-show"]() {
  658. return this.isMenuOpen(
  659. this.$el.dataset.playlistName,
  660. parseInt(this.$el.dataset.playlistIndex),
  661. );
  662. },
  663. },
  664. // View navigation methods
  665. showHistory() {
  666. this.currentView = "history";
  667. this.loadHistory(); // Refresh history data when switching to history view
  668. },
  669. showPlaylists() {
  670. this.currentView = "playlists";
  671. },
  672. showPlaylist(playlistName) {
  673. this.currentView = "playlist";
  674. this.currentPlaylistName = playlistName;
  675. this.updateCurrentPlaylistVideos();
  676. },
  677. // Methods for truncated display
  678. shouldShowTruncation(playlistName) {
  679. const currentIndex = this.currentIndices[playlistName] || 0;
  680. return currentIndex > 0;
  681. },
  682. getTruncationText(playlistName) {
  683. const currentIndex = this.currentIndices[playlistName] || 0;
  684. const count = currentIndex;
  685. return `(${count} previous video${count === 1 ? "" : "s"})`;
  686. },
  687. getVisibleVideos(playlistName, videos) {
  688. const currentIndex = this.currentIndices[playlistName] || 0;
  689. // Show from current video onwards, but keep original indices
  690. return videos.slice(currentIndex).map((video, index) => ({
  691. ...video,
  692. originalIndex: currentIndex + index,
  693. }));
  694. },
  695. getCurrentPlaylistVideos() {
  696. if (
  697. !this.currentPlaylistName ||
  698. !this.playlists[this.currentPlaylistName]
  699. ) {
  700. return [];
  701. }
  702. return this.playlists[this.currentPlaylistName];
  703. },
  704. // Button bindings for navigation
  705. historyButton: {
  706. ["@click"]() {
  707. this.showHistory();
  708. },
  709. },
  710. backButton: {
  711. ["@click"]() {
  712. this.showPlaylists();
  713. },
  714. },
  715. // Event handlers for playlist navigation
  716. playlistNameClick: {
  717. ["@click"]() {
  718. const playlistName = this.$el.dataset.playlistName;
  719. this.showPlaylist(playlistName);
  720. },
  721. },
  722. truncatedVideosClick: {
  723. ["@click"]() {
  724. const playlistName = this.$el.dataset.playlistName;
  725. this.showPlaylist(playlistName);
  726. },
  727. },
  728. truncatedVideosClick: {
  729. ["@click"]() {
  730. const playlistName = this.$el.dataset.playlistName;
  731. this.showPlaylist(playlistName);
  732. },
  733. },
  734. truncatedVideosDisplay: {
  735. ["x-show"]() {
  736. const playlistName = this.$el.dataset.playlistName;
  737. const playlistData = this.playlistsForDisplay.find(
  738. (p) => p.name === playlistName,
  739. );
  740. return playlistData ? playlistData.shouldShowTruncation : false;
  741. },
  742. ["@click"]() {
  743. const playlistName = this.$el.dataset.playlistName;
  744. this.showPlaylist(playlistName);
  745. },
  746. },
  747. // CSP-compliant view bindings
  748. playlistsHeader: {
  749. ["x-show"]() {
  750. return this.currentView === "playlists";
  751. },
  752. },
  753. historyHeader: {
  754. ["x-show"]() {
  755. return this.currentView === "history";
  756. },
  757. },
  758. playlistViewHeader: {
  759. ["x-show"]() {
  760. return this.currentView === "playlist";
  761. },
  762. },
  763. playlistsContainer: {
  764. ["x-show"]() {
  765. return this.currentView === "playlists";
  766. },
  767. },
  768. historyContainer: {
  769. ["x-show"]() {
  770. return this.currentView === "history";
  771. },
  772. },
  773. playlistViewContainer: {
  774. ["x-show"]() {
  775. return this.currentView === "playlist";
  776. },
  777. },
  778. exportContainer: {
  779. ["x-show"]() {
  780. return this.currentView === "playlists";
  781. },
  782. },
  783. // History-specific bindings for CSP compliance
  784. historyEmptyState: {
  785. ["x-show"]() {
  786. return this.sortedHistory.length === 0;
  787. },
  788. },
  789. // Playlist view-specific bindings for CSP compliance
  790. playlistViewEmptyState: {
  791. ["x-show"]() {
  792. return this.currentPlaylistVideos.length === 0;
  793. },
  794. },
  795. // Tag chip bindings for CSP compliance
  796. tagChip: {
  797. ["@click"]() {
  798. const videoId = this.$el.dataset.videoId;
  799. const tag = this.$el.dataset.tag;
  800. this.toggleTag(videoId, tag);
  801. },
  802. [":class"]() {
  803. const videoId = this.$el.dataset.videoId;
  804. const tag = this.$el.dataset.tag;
  805. return {
  806. active: this.isTagActive(videoId, tag),
  807. };
  808. },
  809. },
  810. // Add current page button binding
  811. addCurrentPageButton: {
  812. ["@click"]() {
  813. this.addCurrentPageToPlaylist();
  814. },
  815. [":disabled"]() {
  816. return (
  817. !this.currentTab ||
  818. !this.isCurrentTabYoutube ||
  819. !this.currentPlaylistName
  820. );
  821. },
  822. [":class"]() {
  823. return {
  824. disabled:
  825. !this.currentTab ||
  826. !this.isCurrentTabYoutube ||
  827. !this.currentPlaylistName,
  828. };
  829. },
  830. },
  831. }));
  832. });