1
0

index.js 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444
  1. // Global variables
  2. let allPatterns = [];
  3. let allPatternsWithMetadata = []; // Enhanced pattern data with metadata
  4. let currentSort = { field: 'name', direction: 'asc' };
  5. let currentFilters = { category: 'all' };
  6. // AbortController for cancelling in-flight requests when navigating away
  7. let metadataAbortController = null;
  8. // Helper function to normalize file paths for cross-platform compatibility
  9. function normalizeFilePath(filePath) {
  10. if (!filePath) return '';
  11. // First normalize path separators
  12. let normalized = filePath.replace(/\\/g, '/');
  13. // Remove only the patterns directory prefix, not patterns within the path
  14. if (normalized.startsWith('./patterns/')) {
  15. normalized = normalized.substring(11);
  16. } else if (normalized.startsWith('patterns/')) {
  17. normalized = normalized.substring(9);
  18. }
  19. return normalized;
  20. }
  21. let selectedPattern = null;
  22. let previewObserver = null;
  23. let currentBatch = 0;
  24. const BATCH_SIZE = 40; // Increased batch size for better performance
  25. let previewCache = new Map(); // Simple in-memory cache for preview data
  26. let imageCache = new Map(); // Cache for preloaded images
  27. // Global variables for lazy loading
  28. let pendingPatterns = new Map(); // pattern -> element mapping
  29. let batchTimeout = null;
  30. const INITIAL_BATCH_SIZE = 12; // Smaller initial batch for faster first load
  31. const LAZY_BATCH_SIZE = 5; // Reduced batch size for smoother loading
  32. const MAX_RETRIES = 3; // Maximum number of retries for failed loads
  33. const RETRY_DELAY = 1000; // Delay between retries in ms
  34. // Shared caching for patterns list (persistent across sessions)
  35. const PATTERNS_CACHE_KEY = 'dune_weaver_patterns_cache';
  36. // IndexedDB cache for preview images with size management (shared with playlists page)
  37. const PREVIEW_CACHE_DB_NAME = 'dune_weaver_previews';
  38. const PREVIEW_CACHE_DB_VERSION = 1;
  39. const PREVIEW_CACHE_STORE_NAME = 'previews';
  40. const MAX_CACHE_SIZE_MB = 200;
  41. const MAX_CACHE_SIZE_BYTES = MAX_CACHE_SIZE_MB * 1024 * 1024;
  42. let previewCacheDB = null;
  43. // Define constants for log message types
  44. const LOG_TYPE = {
  45. SUCCESS: 'success',
  46. WARNING: 'warning',
  47. ERROR: 'error',
  48. INFO: 'info',
  49. DEBUG: 'debug'
  50. };
  51. // Cache progress storage keys
  52. const CACHE_PROGRESS_KEY = 'dune_weaver_cache_progress';
  53. const CACHE_TIMESTAMP_KEY = 'dune_weaver_cache_timestamp';
  54. const CACHE_PROGRESS_EXPIRY = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
  55. // Animated Preview Variables
  56. let animatedPreviewData = null;
  57. let animationFrameId = null;
  58. let isPlaying = false;
  59. let currentProgress = 0;
  60. let animationSpeed = 1;
  61. let lastTimestamp = 0;
  62. // Function to show status message
  63. function showStatusMessage(message, type = 'success') {
  64. const statusContainer = document.getElementById('status-message-container');
  65. const statusMessage = document.getElementById('status-message');
  66. if (!statusContainer || !statusMessage) return;
  67. // Set message and color based on type
  68. statusMessage.textContent = message;
  69. statusMessage.className = `text-base font-semibold opacity-0 transform -translate-y-2 transition-all duration-300 ease-in-out px-4 py-2 rounded-lg shadow-lg ${
  70. type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' :
  71. type === 'error' ? 'bg-red-50 text-red-700 border border-red-200' :
  72. type === 'warning' ? 'bg-yellow-50 text-yellow-700 border border-yellow-200' :
  73. 'bg-blue-50 text-blue-700 border border-blue-200'
  74. }`;
  75. // Show message with animation
  76. requestAnimationFrame(() => {
  77. statusMessage.classList.remove('opacity-0', '-translate-y-2');
  78. statusMessage.classList.add('opacity-100', 'translate-y-0');
  79. });
  80. // Hide message after 5 seconds
  81. setTimeout(() => {
  82. statusMessage.classList.remove('opacity-100', 'translate-y-0');
  83. statusMessage.classList.add('opacity-0', '-translate-y-2');
  84. }, 5000);
  85. }
  86. // Function to log messages
  87. function logMessage(message, type = LOG_TYPE.DEBUG) {
  88. console.log(`[${type}] ${message}`);
  89. }
  90. // Initialize IndexedDB for preview caching (shared with playlists page)
  91. async function initPreviewCacheDB() {
  92. if (previewCacheDB) return previewCacheDB;
  93. return new Promise((resolve, reject) => {
  94. const request = indexedDB.open(PREVIEW_CACHE_DB_NAME, PREVIEW_CACHE_DB_VERSION);
  95. request.onerror = () => {
  96. logMessage('Failed to open preview cache database', LOG_TYPE.ERROR);
  97. reject(request.error);
  98. };
  99. request.onsuccess = () => {
  100. previewCacheDB = request.result;
  101. logMessage('Preview cache database opened successfully', LOG_TYPE.DEBUG);
  102. resolve(previewCacheDB);
  103. };
  104. request.onupgradeneeded = (event) => {
  105. const db = event.target.result;
  106. // Create object store for preview cache
  107. const store = db.createObjectStore(PREVIEW_CACHE_STORE_NAME, { keyPath: 'pattern' });
  108. store.createIndex('lastAccessed', 'lastAccessed', { unique: false });
  109. store.createIndex('size', 'size', { unique: false });
  110. logMessage('Preview cache database schema created', LOG_TYPE.DEBUG);
  111. };
  112. });
  113. }
  114. // Get preview from IndexedDB cache
  115. async function getPreviewFromCache(pattern) {
  116. try {
  117. if (!previewCacheDB) await initPreviewCacheDB();
  118. const transaction = previewCacheDB.transaction([PREVIEW_CACHE_STORE_NAME], 'readwrite');
  119. const store = transaction.objectStore(PREVIEW_CACHE_STORE_NAME);
  120. return new Promise((resolve, reject) => {
  121. const request = store.get(pattern);
  122. request.onsuccess = () => {
  123. const result = request.result;
  124. if (result) {
  125. // Update last accessed time
  126. result.lastAccessed = Date.now();
  127. store.put(result);
  128. resolve(result.data);
  129. } else {
  130. resolve(null);
  131. }
  132. };
  133. request.onerror = () => reject(request.error);
  134. });
  135. } catch (error) {
  136. logMessage(`Error getting preview from cache: ${error.message}`, LOG_TYPE.WARNING);
  137. return null;
  138. }
  139. }
  140. // Clear a specific pattern from IndexedDB cache
  141. async function clearPatternFromIndexedDB(pattern) {
  142. try {
  143. if (!previewCacheDB) await initPreviewCacheDB();
  144. const transaction = previewCacheDB.transaction([PREVIEW_CACHE_STORE_NAME], 'readwrite');
  145. const store = transaction.objectStore(PREVIEW_CACHE_STORE_NAME);
  146. await new Promise((resolve, reject) => {
  147. const deleteRequest = store.delete(pattern);
  148. deleteRequest.onsuccess = () => {
  149. logMessage(`Cleared ${pattern} from IndexedDB cache`, LOG_TYPE.DEBUG);
  150. resolve();
  151. };
  152. deleteRequest.onerror = () => {
  153. logMessage(`Failed to clear ${pattern} from IndexedDB: ${deleteRequest.error}`, LOG_TYPE.WARNING);
  154. reject(deleteRequest.error);
  155. };
  156. });
  157. } catch (error) {
  158. logMessage(`Error clearing pattern from IndexedDB: ${error.message}`, LOG_TYPE.WARNING);
  159. }
  160. }
  161. // Save preview to IndexedDB cache with size management
  162. async function savePreviewToCache(pattern, previewData) {
  163. try {
  164. if (!previewCacheDB) await initPreviewCacheDB();
  165. // Validate preview data before attempting to fetch
  166. if (!previewData || !previewData.image_data) {
  167. logMessage(`Invalid preview data for ${pattern}, skipping cache save`, LOG_TYPE.WARNING);
  168. return;
  169. }
  170. // Convert preview URL to blob for size calculation
  171. const response = await fetch(previewData.image_data);
  172. const blob = await response.blob();
  173. const size = blob.size;
  174. // Check if we need to free up space
  175. await managePreviewCacheSize(size);
  176. const cacheEntry = {
  177. pattern: pattern,
  178. data: previewData,
  179. size: size,
  180. lastAccessed: Date.now(),
  181. created: Date.now()
  182. };
  183. const transaction = previewCacheDB.transaction([PREVIEW_CACHE_STORE_NAME], 'readwrite');
  184. const store = transaction.objectStore(PREVIEW_CACHE_STORE_NAME);
  185. return new Promise((resolve, reject) => {
  186. const request = store.put(cacheEntry);
  187. request.onsuccess = () => {
  188. logMessage(`Preview cached for ${pattern} (${(size / 1024).toFixed(1)}KB)`, LOG_TYPE.DEBUG);
  189. resolve();
  190. };
  191. request.onerror = () => reject(request.error);
  192. });
  193. } catch (error) {
  194. logMessage(`Error saving preview to cache: ${error.message}`, LOG_TYPE.WARNING);
  195. }
  196. }
  197. // Manage cache size by removing least recently used items
  198. async function managePreviewCacheSize(newItemSize) {
  199. try {
  200. const currentSize = await getPreviewCacheSize();
  201. if (currentSize + newItemSize <= MAX_CACHE_SIZE_BYTES) {
  202. return; // No cleanup needed
  203. }
  204. logMessage(`Cache size would exceed limit (${((currentSize + newItemSize) / 1024 / 1024).toFixed(1)}MB), cleaning up...`, LOG_TYPE.DEBUG);
  205. const transaction = previewCacheDB.transaction([PREVIEW_CACHE_STORE_NAME], 'readwrite');
  206. const store = transaction.objectStore(PREVIEW_CACHE_STORE_NAME);
  207. const index = store.index('lastAccessed');
  208. // Get all entries sorted by last accessed (oldest first)
  209. const entries = await new Promise((resolve, reject) => {
  210. const request = index.getAll();
  211. request.onsuccess = () => resolve(request.result);
  212. request.onerror = () => reject(request.error);
  213. });
  214. // Sort by last accessed time (oldest first)
  215. entries.sort((a, b) => a.lastAccessed - b.lastAccessed);
  216. let freedSpace = 0;
  217. const targetSpace = newItemSize + (MAX_CACHE_SIZE_BYTES * 0.1); // Free 10% extra buffer
  218. for (const entry of entries) {
  219. if (freedSpace >= targetSpace) break;
  220. await new Promise((resolve, reject) => {
  221. const deleteRequest = store.delete(entry.pattern);
  222. deleteRequest.onsuccess = () => {
  223. freedSpace += entry.size;
  224. logMessage(`Evicted cached preview for ${entry.pattern} (${(entry.size / 1024).toFixed(1)}KB)`, LOG_TYPE.DEBUG);
  225. resolve();
  226. };
  227. deleteRequest.onerror = () => reject(deleteRequest.error);
  228. });
  229. }
  230. logMessage(`Freed ${(freedSpace / 1024 / 1024).toFixed(1)}MB from preview cache`, LOG_TYPE.DEBUG);
  231. } catch (error) {
  232. logMessage(`Error managing cache size: ${error.message}`, LOG_TYPE.WARNING);
  233. }
  234. }
  235. // Get current cache size
  236. async function getPreviewCacheSize() {
  237. try {
  238. if (!previewCacheDB) return 0;
  239. const transaction = previewCacheDB.transaction([PREVIEW_CACHE_STORE_NAME], 'readonly');
  240. const store = transaction.objectStore(PREVIEW_CACHE_STORE_NAME);
  241. return new Promise((resolve, reject) => {
  242. const request = store.getAll();
  243. request.onsuccess = () => {
  244. const totalSize = request.result.reduce((sum, entry) => sum + (entry.size || 0), 0);
  245. resolve(totalSize);
  246. };
  247. request.onerror = () => reject(request.error);
  248. });
  249. } catch (error) {
  250. logMessage(`Error getting cache size: ${error.message}`, LOG_TYPE.WARNING);
  251. return 0;
  252. }
  253. }
  254. // Preload images in batch
  255. async function preloadImages(urls) {
  256. const promises = urls.map(url => {
  257. return new Promise((resolve, reject) => {
  258. if (imageCache.has(url)) {
  259. resolve(imageCache.get(url));
  260. return;
  261. }
  262. const img = new Image();
  263. img.onload = () => {
  264. imageCache.set(url, img);
  265. resolve(img);
  266. };
  267. img.onerror = reject;
  268. img.src = url;
  269. });
  270. });
  271. return Promise.allSettled(promises);
  272. }
  273. // Initialize Intersection Observer for lazy loading
  274. function initPreviewObserver() {
  275. if (previewObserver) {
  276. previewObserver.disconnect();
  277. }
  278. previewObserver = new IntersectionObserver((entries) => {
  279. entries.forEach(entry => {
  280. if (entry.isIntersecting) {
  281. const previewContainer = entry.target;
  282. const pattern = previewContainer.dataset.pattern;
  283. if (pattern) {
  284. addPatternToBatch(pattern, previewContainer);
  285. previewObserver.unobserve(previewContainer);
  286. }
  287. }
  288. });
  289. }, {
  290. rootMargin: '200px 0px',
  291. threshold: 0.1
  292. });
  293. }
  294. // Add pattern to pending batch for efficient loading
  295. async function addPatternToBatch(pattern, element) {
  296. // Check in-memory cache first
  297. if (previewCache.has(pattern)) {
  298. const previewData = previewCache.get(pattern);
  299. if (previewData && !previewData.error) {
  300. if (element) {
  301. updatePreviewElement(element, previewData.image_data);
  302. }
  303. }
  304. return;
  305. }
  306. // Check IndexedDB cache
  307. const cachedData = await getPreviewFromCache(pattern);
  308. if (cachedData && !cachedData.error) {
  309. // Add to in-memory cache for faster access
  310. previewCache.set(pattern, cachedData);
  311. if (element) {
  312. updatePreviewElement(element, cachedData.image_data);
  313. }
  314. return;
  315. }
  316. // Check if this is a newly uploaded pattern
  317. const isNewUpload = element?.dataset.isNewUpload === 'true';
  318. // Reset retry flags when starting fresh
  319. if (element) {
  320. element.dataset.retryCount = '0';
  321. element.dataset.hasTriedIndividual = 'false';
  322. }
  323. // Add loading indicator with better styling
  324. if (!element.querySelector('img')) {
  325. const loadingText = isNewUpload ? 'Generating preview...' : 'Loading...';
  326. element.innerHTML = `
  327. <div class="absolute inset-0 flex items-center justify-center bg-slate-100 rounded-full">
  328. <div class="bg-slate-200 rounded-full h-8 w-8 flex items-center justify-center">
  329. <div class="bg-slate-500 rounded-full h-4 w-4"></div>
  330. </div>
  331. </div>
  332. <div class="absolute inset-0 flex items-center justify-center">
  333. <div class="text-xs text-slate-500 mt-12">${loadingText}</div>
  334. </div>
  335. `;
  336. }
  337. // Add to pending batch
  338. pendingPatterns.set(pattern, element);
  339. // Process batch immediately if it's full or if it's a new upload
  340. if (pendingPatterns.size >= LAZY_BATCH_SIZE || isNewUpload) {
  341. processPendingBatch();
  342. } else {
  343. // Set a timeout to process smaller batches if they don't fill up
  344. if (batchTimeout) {
  345. clearTimeout(batchTimeout);
  346. }
  347. batchTimeout = setTimeout(() => {
  348. if (pendingPatterns.size > 0) {
  349. processPendingBatch();
  350. }
  351. }, 500); // Process after 500ms if batch doesn't fill up
  352. }
  353. }
  354. // Update preview element with smooth transition
  355. function updatePreviewElement(element, imageUrl) {
  356. const img = new Image();
  357. img.onload = () => {
  358. element.innerHTML = '';
  359. element.appendChild(img);
  360. img.className = 'w-full h-full object-contain transition-opacity duration-300';
  361. img.style.opacity = '0';
  362. requestAnimationFrame(() => {
  363. img.style.opacity = '1';
  364. });
  365. // Mark element as loaded to prevent duplicate loading attempts
  366. element.dataset.loaded = 'true';
  367. };
  368. img.src = imageUrl;
  369. img.alt = 'Pattern Preview';
  370. }
  371. // Process pending patterns in batches
  372. async function processPendingBatch() {
  373. if (pendingPatterns.size === 0) return;
  374. // Clear any pending timeout since we're processing now
  375. if (batchTimeout) {
  376. clearTimeout(batchTimeout);
  377. batchTimeout = null;
  378. }
  379. // Create a copy of current pending patterns and clear the original
  380. const currentBatch = new Map(pendingPatterns);
  381. pendingPatterns.clear();
  382. const patternsToLoad = Array.from(currentBatch.keys());
  383. try {
  384. logMessage(`Loading batch of ${patternsToLoad.length} pattern previews`, LOG_TYPE.DEBUG);
  385. const response = await fetch('/preview_thr_batch', {
  386. method: 'POST',
  387. headers: { 'Content-Type': 'application/json' },
  388. body: JSON.stringify({ file_names: patternsToLoad })
  389. });
  390. if (response.ok) {
  391. const results = await response.json();
  392. // Process all results
  393. for (const [pattern, data] of Object.entries(results)) {
  394. const element = currentBatch.get(pattern);
  395. if (data && !data.error && data.image_data) {
  396. // Cache in memory with size limit
  397. if (previewCache.size > 100) { // Limit cache size
  398. const oldestKey = previewCache.keys().next().value;
  399. previewCache.delete(oldestKey);
  400. }
  401. previewCache.set(pattern, data);
  402. // Save to IndexedDB cache for persistence
  403. await savePreviewToCache(pattern, data);
  404. if (element) {
  405. updatePreviewElement(element, data.image_data);
  406. }
  407. } else {
  408. handleLoadError(pattern, element, data?.error || 'Failed to load preview');
  409. }
  410. }
  411. }
  412. } catch (error) {
  413. logMessage(`Error loading preview batch: ${error.message}`, LOG_TYPE.ERROR);
  414. // Handle error for each pattern in batch
  415. for (const pattern of patternsToLoad) {
  416. const element = currentBatch.get(pattern);
  417. handleLoadError(pattern, element, error.message);
  418. }
  419. }
  420. }
  421. // Trigger preview loading for currently visible patterns
  422. async function triggerPreviewLoadingForVisible() {
  423. // Get all pattern cards currently in the DOM
  424. const patternCards = document.querySelectorAll('.pattern-card');
  425. // Collect all patterns that need checking
  426. const patternsToCheck = [];
  427. patternCards.forEach(card => {
  428. const pattern = card.dataset.pattern;
  429. const previewContainer = card.querySelector('.pattern-preview');
  430. // Check if this pattern needs preview loading (only check in-memory cache here)
  431. if (pattern && !previewCache.has(pattern) && !pendingPatterns.has(pattern)) {
  432. patternsToCheck.push({ pattern, previewContainer });
  433. }
  434. });
  435. // Wait for all IndexedDB cache checks to complete before processing batch
  436. // This prevents unnecessary API calls for patterns that are already cached in IndexedDB
  437. await Promise.all(patternsToCheck.map(({ pattern, previewContainer }) =>
  438. addPatternToBatch(pattern, previewContainer)
  439. ));
  440. // Process any pending previews that weren't found in cache
  441. if (pendingPatterns.size > 0) {
  442. processPendingBatch();
  443. }
  444. }
  445. // Load individual pattern preview (fallback when batch loading fails)
  446. async function loadIndividualPreview(pattern, element) {
  447. try {
  448. logMessage(`Loading individual preview for ${pattern}`, LOG_TYPE.DEBUG);
  449. const response = await fetch('/preview_thr_batch', {
  450. method: 'POST',
  451. headers: { 'Content-Type': 'application/json' },
  452. body: JSON.stringify({ file_names: [pattern] })
  453. });
  454. if (response.ok) {
  455. const results = await response.json();
  456. const data = results[pattern];
  457. if (data && !data.error && data.image_data) {
  458. // Cache in memory with size limit
  459. if (previewCache.size > 100) { // Limit cache size
  460. const oldestKey = previewCache.keys().next().value;
  461. previewCache.delete(oldestKey);
  462. }
  463. previewCache.set(pattern, data);
  464. // Save to IndexedDB cache for persistence
  465. await savePreviewToCache(pattern, data);
  466. if (element) {
  467. updatePreviewElement(element, data.image_data);
  468. }
  469. logMessage(`Individual preview loaded successfully for ${pattern}`, LOG_TYPE.DEBUG);
  470. } else {
  471. throw new Error(data?.error || 'Failed to load preview data');
  472. }
  473. } else {
  474. throw new Error(`HTTP error! status: ${response.status}`);
  475. }
  476. } catch (error) {
  477. logMessage(`Error loading individual preview for ${pattern}: ${error.message}`, LOG_TYPE.ERROR);
  478. // Continue with normal error handling
  479. handleLoadError(pattern, element, error.message);
  480. }
  481. }
  482. // Handle load errors with retry logic
  483. function handleLoadError(pattern, element, error) {
  484. const retryCount = element.dataset.retryCount || 0;
  485. const isNewUpload = element.dataset.isNewUpload === 'true';
  486. const hasTriedIndividual = element.dataset.hasTriedIndividual === 'true';
  487. // Use longer delays for newly uploaded patterns
  488. const retryDelay = isNewUpload ? RETRY_DELAY * 2 : RETRY_DELAY;
  489. const maxRetries = isNewUpload ? MAX_RETRIES * 2 : MAX_RETRIES;
  490. if (retryCount < maxRetries) {
  491. // Update retry count
  492. element.dataset.retryCount = parseInt(retryCount) + 1;
  493. // Determine retry strategy
  494. let retryStrategy = 'batch';
  495. if (retryCount >= 1 && !hasTriedIndividual) {
  496. // After first batch attempt fails, try individual loading
  497. retryStrategy = 'individual';
  498. element.dataset.hasTriedIndividual = 'true';
  499. }
  500. // Show retry message with different text for new uploads and retry strategies
  501. let retryText;
  502. if (isNewUpload) {
  503. retryText = retryStrategy === 'individual' ?
  504. `Trying individual load... (${retryCount + 1}/${maxRetries})` :
  505. `Generating preview... (${retryCount + 1}/${maxRetries})`;
  506. } else {
  507. retryText = retryStrategy === 'individual' ?
  508. `Trying individual load... (${retryCount + 1}/${maxRetries})` :
  509. `Retrying... (${retryCount + 1}/${maxRetries})`;
  510. }
  511. element.innerHTML = `
  512. <div class="absolute inset-0 flex items-center justify-center bg-slate-100 rounded-full">
  513. <div class="text-xs text-slate-500 text-center">
  514. <div>${isNewUpload ? 'Processing new pattern' : 'Failed to load'}</div>
  515. <div>${retryText}</div>
  516. </div>
  517. </div>
  518. `;
  519. // Retry after delay with appropriate strategy
  520. setTimeout(() => {
  521. if (retryStrategy === 'individual') {
  522. loadIndividualPreview(pattern, element);
  523. } else {
  524. addPatternToBatch(pattern, element);
  525. }
  526. }, retryDelay);
  527. } else {
  528. // Show final error state
  529. element.innerHTML = `
  530. <div class="absolute inset-0 flex items-center justify-center bg-slate-100 rounded-full">
  531. <div class="text-xs text-slate-500 text-center">
  532. <div>Failed to load</div>
  533. <div>Click to retry</div>
  534. </div>
  535. </div>
  536. `;
  537. // Add click handler for manual retry
  538. element.onclick = () => {
  539. element.dataset.retryCount = '0';
  540. element.dataset.hasTriedIndividual = 'false';
  541. addPatternToBatch(pattern, element);
  542. };
  543. }
  544. previewCache.set(pattern, { error: true });
  545. }
  546. // Load and display patterns
  547. async function loadPatterns(forceRefresh = false) {
  548. try {
  549. logMessage('Loading patterns...', LOG_TYPE.INFO);
  550. // First load basic patterns list for fast initial display
  551. logMessage('Fetching basic patterns list from server', LOG_TYPE.DEBUG);
  552. const basicPatterns = await getCachedPatternFiles(forceRefresh);
  553. const thrPatterns = basicPatterns.filter(file => file.endsWith('.thr'));
  554. logMessage(`Received ${thrPatterns.length} basic patterns from server`, LOG_TYPE.INFO);
  555. // Store basic patterns and display immediately
  556. let patterns = [...thrPatterns];
  557. allPatterns = patterns;
  558. // Sort patterns alphabetically to match final enhanced sorting
  559. const sortedPatterns = patterns.sort((a, b) => a.localeCompare(b));
  560. allPatterns = sortedPatterns;
  561. // Display basic patterns immediately for fast initial load
  562. logMessage('Displaying initial patterns...', LOG_TYPE.INFO);
  563. displayPatternBatch();
  564. logMessage('Initial patterns loaded successfully.', LOG_TYPE.SUCCESS);
  565. // Load metadata in background for enhanced features
  566. setTimeout(async () => {
  567. try {
  568. // Cancel any previous metadata loading request
  569. if (metadataAbortController) {
  570. metadataAbortController.abort();
  571. }
  572. // Create new AbortController for this request with timeout
  573. metadataAbortController = new AbortController();
  574. // Set a timeout to prevent hanging on slow Pi systems
  575. const timeoutId = setTimeout(() => {
  576. metadataAbortController.abort();
  577. logMessage('Metadata loading timed out after 30 seconds', LOG_TYPE.WARNING);
  578. }, 30000); // 30 second timeout
  579. logMessage('Loading enhanced metadata...', LOG_TYPE.DEBUG);
  580. const metadataResponse = await fetch('/list_theta_rho_files_with_metadata', {
  581. signal: metadataAbortController.signal,
  582. headers: {
  583. 'Cache-Control': 'no-cache'
  584. }
  585. });
  586. // Clear timeout if request succeeds
  587. clearTimeout(timeoutId);
  588. const patternsWithMetadata = await metadataResponse.json();
  589. // Store enhanced patterns data
  590. allPatternsWithMetadata = [...patternsWithMetadata];
  591. // Update category filter dropdown now that we have metadata
  592. updateBrowseCategoryFilter();
  593. // Enable sort controls and display patterns consistently
  594. enableSortControls();
  595. logMessage(`Enhanced metadata loaded for ${patternsWithMetadata.length} patterns`, LOG_TYPE.SUCCESS);
  596. // Clear the controller reference since request completed
  597. metadataAbortController = null;
  598. } catch (metadataError) {
  599. if (metadataError.name === 'AbortError') {
  600. logMessage('Metadata loading cancelled or timed out', LOG_TYPE.WARNING);
  601. } else {
  602. logMessage(`Failed to load enhanced metadata: ${metadataError.message}`, LOG_TYPE.WARNING);
  603. }
  604. // Create basic metadata from file list to populate categories
  605. if (allPatterns && allPatterns.length > 0) {
  606. allPatternsWithMetadata = allPatterns.map(pattern => {
  607. const pathParts = pattern.split('/');
  608. const category = pathParts.length > 1 ? pathParts.slice(0, -1).join('/') : 'root';
  609. const fileName = pathParts[pathParts.length - 1].replace('.thr', '');
  610. return {
  611. path: pattern,
  612. name: fileName,
  613. category: category,
  614. date_modified: 0,
  615. coordinates_count: 0
  616. };
  617. });
  618. // Update category filter with basic data
  619. updateBrowseCategoryFilter();
  620. logMessage('Using basic category data (metadata unavailable)', LOG_TYPE.INFO);
  621. }
  622. metadataAbortController = null;
  623. }
  624. }, 100); // Small delay to let initial render complete
  625. if (forceRefresh) {
  626. showStatusMessage('Patterns list refreshed successfully', 'success');
  627. }
  628. } catch (error) {
  629. logMessage(`Error loading patterns: ${error.message}`, LOG_TYPE.ERROR);
  630. console.error('Full error:', error);
  631. showStatusMessage('Failed to load patterns', 'error');
  632. }
  633. }
  634. // Display a batch of patterns with improved initial load
  635. function displayPatternBatch() {
  636. const patternGrid = document.querySelector('.grid');
  637. if (!patternGrid) {
  638. logMessage('Pattern grid not found in the DOM', LOG_TYPE.ERROR);
  639. return;
  640. }
  641. const start = currentBatch * BATCH_SIZE;
  642. const end = Math.min(start + BATCH_SIZE, allPatterns.length);
  643. const batchPatterns = allPatterns.slice(start, end);
  644. // Display batch patterns
  645. batchPatterns.forEach(pattern => {
  646. const patternCard = createPatternCard(pattern);
  647. patternGrid.appendChild(patternCard);
  648. });
  649. // If there are more patterns to load, set up the observer for the last few cards
  650. if (end < allPatterns.length) {
  651. const lastCards = Array.from(patternGrid.children).slice(-3); // Observe last 3 cards
  652. lastCards.forEach(card => {
  653. const observer = new IntersectionObserver((entries) => {
  654. if (entries[0].isIntersecting) {
  655. currentBatch++;
  656. displayPatternBatch();
  657. observer.disconnect();
  658. }
  659. }, {
  660. rootMargin: '200px 0px',
  661. threshold: 0.1
  662. });
  663. observer.observe(card);
  664. });
  665. }
  666. }
  667. // Create a pattern card element
  668. function createPatternCard(pattern) {
  669. const card = document.createElement('div');
  670. card.className = 'pattern-card group relative flex flex-col items-center gap-3 bg-gray-50';
  671. card.dataset.pattern = pattern;
  672. // Create preview container with proper styling for loading indicator
  673. const previewContainer = document.createElement('div');
  674. previewContainer.className = 'w-32 h-32 rounded-full shadow-md relative pattern-preview';
  675. previewContainer.dataset.pattern = pattern;
  676. // Add loading indicator
  677. previewContainer.innerHTML = '<div class="absolute inset-0 flex items-center justify-center"><div class="bg-slate-200 rounded-full h-8 w-8 flex items-center justify-center"><div class="bg-slate-500 rounded-full h-4 w-4"></div></div></div>';
  678. // Add play button overlay (centered, hidden by default, shown on hover)
  679. const playOverlay = document.createElement('div');
  680. playOverlay.className = 'absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 cursor-pointer';
  681. playOverlay.innerHTML = '<div class="bg-white rounded-full p-2 shadow-lg flex items-center justify-center w-10 h-10"><span class="material-icons text-lg text-gray-800">play_arrow</span></div>';
  682. playOverlay.title = 'Preview pattern';
  683. playOverlay.addEventListener('click', (e) => {
  684. e.stopPropagation(); // Prevent card selection
  685. openAnimatedPreview(pattern);
  686. });
  687. previewContainer.appendChild(playOverlay);
  688. // Add heart favorite button (top-right corner)
  689. const heartButton = document.createElement('div');
  690. const isAlreadyFavorite = favoritePatterns.has(pattern);
  691. const heartOpacity = isAlreadyFavorite ? 'opacity-100' : 'opacity-0 group-hover:opacity-100';
  692. heartButton.className = `absolute top-2 right-2 w-7 h-7 cursor-pointer ${heartOpacity} transition-opacity duration-200 z-10 bg-white/90 rounded-full shadow-sm flex items-center justify-center`;
  693. const heartIcon = isAlreadyFavorite ? 'favorite' : 'favorite_border';
  694. const heartColor = isAlreadyFavorite ? 'text-red-500 hover:text-red-600' : 'text-gray-400 hover:text-red-500';
  695. heartButton.innerHTML = `<span class="material-icons text-lg ${heartColor} transition-colors" id="heart-${pattern.replace(/[^a-zA-Z0-9]/g, '_')}">${heartIcon}</span>`;
  696. heartButton.title = isAlreadyFavorite ? 'Remove from favorites' : 'Add to favorites';
  697. heartButton.addEventListener('click', (e) => {
  698. e.stopPropagation(); // Prevent card selection
  699. toggleFavorite(pattern);
  700. });
  701. // Note: Heart button will be added to card, not previewContainer to avoid circular clipping
  702. // Create pattern name
  703. const patternName = document.createElement('p');
  704. patternName.className = 'text-gray-700 text-sm font-medium text-center truncate w-full';
  705. patternName.textContent = pattern.replace('.thr', '').split('/').pop();
  706. // Add click handler
  707. card.onclick = () => selectPattern(pattern, card);
  708. // Check if preview is already in cache
  709. const previewData = previewCache.get(pattern);
  710. if (previewData && !previewData.error && previewData.image_data) {
  711. updatePreviewElement(previewContainer, previewData.image_data);
  712. } else {
  713. // Start observing the preview container for lazy loading
  714. previewObserver.observe(previewContainer);
  715. }
  716. card.appendChild(previewContainer);
  717. card.appendChild(patternName);
  718. // Add heart button to card (not previewContainer) to avoid circular clipping
  719. card.appendChild(heartButton);
  720. return card;
  721. }
  722. // Select a pattern
  723. function selectPattern(pattern, card) {
  724. // Remove selected class from all cards
  725. document.querySelectorAll('.pattern-card').forEach(c => {
  726. c.classList.remove('selected');
  727. });
  728. // Add selected class to clicked card
  729. card.classList.add('selected');
  730. // Show pattern preview
  731. showPatternPreview(pattern);
  732. }
  733. // Show pattern preview
  734. async function showPatternPreview(pattern) {
  735. try {
  736. // Check in-memory cache first
  737. let data = previewCache.get(pattern);
  738. // If not in cache, fetch it
  739. if (!data) {
  740. const response = await fetch('/preview_thr_batch', {
  741. method: 'POST',
  742. headers: { 'Content-Type': 'application/json' },
  743. body: JSON.stringify({ file_names: [pattern] })
  744. });
  745. if (!response.ok) {
  746. throw new Error(`HTTP error! status: ${response.status}`);
  747. }
  748. const results = await response.json();
  749. data = results[pattern];
  750. if (data && !data.error) {
  751. // Cache in memory
  752. previewCache.set(pattern, data);
  753. } else {
  754. throw new Error(data?.error || 'Failed to get preview data');
  755. }
  756. }
  757. const previewPanel = document.getElementById('patternPreviewPanel');
  758. const layoutContainer = document.querySelector('.layout-content-container');
  759. // Update preview content
  760. if (data.image_data) {
  761. document.getElementById('patternPreviewImage').src = data.image_data;
  762. }
  763. // Set pattern name in the preview panel
  764. const patternName = pattern.replace('.thr', '').split('/').pop();
  765. document.getElementById('patternPreviewTitle').textContent = patternName;
  766. // Format and display coordinates
  767. const formatCoordinate = (coord) => {
  768. if (!coord) return '(0, 0)';
  769. const x = coord.x !== undefined ? coord.x.toFixed(1) : '0.0';
  770. const y = coord.y !== undefined ? coord.y.toFixed(1) : '0.0';
  771. return `(${x}, ${y})`;
  772. };
  773. document.getElementById('firstCoordinate').textContent = formatCoordinate(data.first_coordinate);
  774. document.getElementById('lastCoordinate').textContent = formatCoordinate(data.last_coordinate);
  775. // Show preview panel
  776. previewPanel.classList.remove('translate-x-full');
  777. if (window.innerWidth >= 1024) {
  778. // For large screens, show preview alongside content
  779. layoutContainer.parentElement.classList.add('preview-open');
  780. previewPanel.classList.remove('lg:opacity-0', 'lg:pointer-events-none');
  781. } else {
  782. // For small screens, show preview as overlay
  783. layoutContainer.parentElement.classList.remove('preview-open');
  784. }
  785. // Setup preview panel events
  786. setupPreviewPanelEvents(pattern);
  787. } catch (error) {
  788. logMessage(`Error showing preview for ${pattern}: ${error.message}`, LOG_TYPE.ERROR);
  789. // Show error state in preview panel instead of hiding it
  790. showPreviewError(pattern, error.message);
  791. }
  792. }
  793. function showPreviewError(pattern, errorMessage) {
  794. const previewPanel = document.getElementById('patternPreviewPanel');
  795. const layoutContainer = document.querySelector('.layout-content-container');
  796. // Show error state in preview panel
  797. const patternName = pattern.replace('.thr', '').split('/').pop();
  798. document.getElementById('patternPreviewTitle').textContent = `Error: ${patternName}`;
  799. // Show error image or placeholder
  800. const img = document.getElementById('patternPreviewImage');
  801. img.src = 'data:image/svg+xml;base64,' + btoa(`
  802. <svg width="400" height="300" xmlns="http://www.w3.org/2000/svg">
  803. <rect width="100%" height="100%" fill="#f3f4f6"/>
  804. <text x="50%" y="40%" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6b7280">
  805. Pattern Not Found
  806. </text>
  807. <text x="50%" y="60%" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#9ca3af">
  808. ${patternName}
  809. </text>
  810. <text x="50%" y="75%" text-anchor="middle" font-family="Arial, sans-serif" font-size="10" fill="#ef4444">
  811. File may have been deleted
  812. </text>
  813. </svg>
  814. `);
  815. // Clear coordinates
  816. document.getElementById('firstCoordinate').textContent = '(0, 0)';
  817. document.getElementById('lastCoordinate').textContent = '(0, 0)';
  818. // Show preview panel with error state
  819. previewPanel.classList.remove('translate-x-full');
  820. if (window.innerWidth >= 1024) {
  821. layoutContainer.parentElement.classList.add('preview-open');
  822. previewPanel.classList.remove('lg:opacity-0', 'lg:pointer-events-none');
  823. } else {
  824. layoutContainer.parentElement.classList.remove('preview-open');
  825. }
  826. // Setup events so user can still close the panel
  827. setupPreviewPanelEvents(pattern);
  828. }
  829. function hidePatternPreview() {
  830. const previewPanel = document.getElementById('patternPreviewPanel');
  831. const layoutContainer = document.querySelector('.layout-content-container');
  832. previewPanel.classList.add('translate-x-full');
  833. if (window.innerWidth >= 1024) {
  834. previewPanel.classList.add('lg:opacity-0', 'lg:pointer-events-none');
  835. }
  836. layoutContainer.parentElement.classList.remove('preview-open');
  837. }
  838. // Add window resize handler
  839. window.addEventListener('resize', () => {
  840. const previewPanel = document.getElementById('patternPreviewPanel');
  841. const layoutContainer = document.querySelector('.layout-content-container');
  842. if (window.innerWidth >= 1024) {
  843. if (!previewPanel.classList.contains('translate-x-full')) {
  844. layoutContainer.parentElement.classList.add('preview-open');
  845. previewPanel.classList.remove('lg:opacity-0', 'lg:pointer-events-none');
  846. }
  847. } else {
  848. layoutContainer.parentElement.classList.remove('preview-open');
  849. previewPanel.classList.add('lg:opacity-0', 'lg:pointer-events-none');
  850. }
  851. // Update category filter display names for new screen size
  852. updateBrowseCategoryFilter();
  853. });
  854. // Setup preview panel events
  855. function setupPreviewPanelEvents(pattern) {
  856. const panel = document.getElementById('patternPreviewPanel');
  857. const closeButton = document.getElementById('closePreviewPanel');
  858. const playButton = document.getElementById('playPattern');
  859. const deleteButton = document.getElementById('deletePattern');
  860. const preExecutionInputs = document.querySelectorAll('input[name="preExecutionAction"]');
  861. const previewPlayOverlay = document.getElementById('previewPlayOverlay');
  862. // Close panel when clicking the close button
  863. closeButton.onclick = () => {
  864. hidePatternPreview();
  865. // Remove selected state from all cards when closing
  866. document.querySelectorAll('.pattern-card').forEach(c => {
  867. c.classList.remove('selected');
  868. });
  869. };
  870. // Handle play button overlay click in preview panel
  871. if (previewPlayOverlay) {
  872. previewPlayOverlay.onclick = () => {
  873. openAnimatedPreview(pattern);
  874. };
  875. }
  876. // Handle play button click
  877. playButton.onclick = async () => {
  878. if (!pattern) {
  879. showStatusMessage('No pattern selected', 'error');
  880. return;
  881. }
  882. try {
  883. // Show the preview modal
  884. if (window.openPlayerPreviewModal) {
  885. window.openPlayerPreviewModal();
  886. }
  887. // Get the selected pre-execution action
  888. const preExecutionInput = document.querySelector('input[name="preExecutionAction"]:checked');
  889. const preExecution = preExecutionInput ? preExecutionInput.value : 'none';
  890. const response = await fetch('/run_theta_rho', {
  891. method: 'POST',
  892. headers: {
  893. 'Content-Type': 'application/json'
  894. },
  895. body: JSON.stringify({
  896. file_name: pattern,
  897. pre_execution: preExecution
  898. })
  899. });
  900. const data = await response.json();
  901. if (response.ok) {
  902. showStatusMessage(`Running pattern: ${pattern.split('/').pop()}`, 'success');
  903. hidePatternPreview();
  904. // Show the preview modal when a pattern starts
  905. if (typeof setModalVisibility === 'function') {
  906. setModalVisibility(true, false);
  907. }
  908. } else {
  909. let errorMsg = data.detail || 'Failed to run pattern';
  910. let errorType = 'error';
  911. // Handle specific error cases with appropriate messaging
  912. if (data.detail === 'Connection not established') {
  913. errorMsg = 'Please connect to the device before running a pattern';
  914. errorType = 'warning';
  915. } else if (response.status === 409) {
  916. errorMsg = 'Another pattern is already running. Please stop the current pattern first.';
  917. errorType = 'warning';
  918. } else if (response.status === 404) {
  919. errorMsg = 'Pattern file not found. Please refresh the page and try again.';
  920. errorType = 'error';
  921. } else if (response.status === 400) {
  922. errorMsg = 'Invalid request. Please check your settings and try again.';
  923. errorType = 'error';
  924. } else if (response.status === 500) {
  925. errorMsg = 'Server error. Please try again later.';
  926. errorType = 'error';
  927. }
  928. showStatusMessage(errorMsg, errorType);
  929. return;
  930. }
  931. } catch (error) {
  932. console.error('Error running pattern:', error);
  933. // Handle network errors specifically
  934. if (error.name === 'TypeError' && error.message.includes('fetch')) {
  935. showStatusMessage('Network error. Please check your connection and try again.', 'error');
  936. } else if (error.message && error.message.includes('409')) {
  937. showStatusMessage('Another pattern is already running', 'warning');
  938. } else if (error.message) {
  939. showStatusMessage(error.message, 'error');
  940. } else {
  941. showStatusMessage('Failed to run pattern', 'error');
  942. }
  943. }
  944. };
  945. // Handle delete button click
  946. deleteButton.onclick = async () => {
  947. if (!pattern.startsWith('custom_patterns/')) {
  948. logMessage('Cannot delete built-in patterns', LOG_TYPE.WARNING);
  949. showStatusMessage('Cannot delete built-in patterns', 'warning');
  950. return;
  951. }
  952. if (confirm('Are you sure you want to delete this pattern?')) {
  953. try {
  954. logMessage(`Deleting pattern: ${pattern}`, LOG_TYPE.INFO);
  955. const response = await fetch('/delete_theta_rho_file', {
  956. method: 'POST',
  957. headers: {
  958. 'Content-Type': 'application/json'
  959. },
  960. body: JSON.stringify({ file_name: pattern })
  961. });
  962. if (!response.ok) {
  963. throw new Error(`HTTP error! status: ${response.status}`);
  964. }
  965. const result = await response.json();
  966. if (result.success) {
  967. logMessage(`Pattern deleted successfully: ${pattern}`, LOG_TYPE.SUCCESS);
  968. showStatusMessage(`Pattern "${pattern.split('/').pop()}" deleted successfully`);
  969. // Invalidate pattern files cache
  970. invalidatePatternFilesCache();
  971. // Clear from in-memory caches
  972. previewCache.delete(pattern);
  973. imageCache.delete(pattern);
  974. // Clear from IndexedDB cache
  975. await clearPatternFromIndexedDB(pattern);
  976. // Clear from localStorage patterns list cache
  977. const cachedPatterns = JSON.parse(localStorage.getItem(PATTERNS_CACHE_KEY) || '{}');
  978. if (cachedPatterns.data) {
  979. const index = cachedPatterns.data.indexOf(pattern);
  980. if (index > -1) {
  981. cachedPatterns.data.splice(index, 1);
  982. localStorage.setItem(PATTERNS_CACHE_KEY, JSON.stringify(cachedPatterns));
  983. }
  984. }
  985. // Remove the pattern card
  986. const selectedCard = document.querySelector('.pattern-card.selected');
  987. if (selectedCard) {
  988. selectedCard.remove();
  989. }
  990. // Close the preview panel
  991. const previewPanel = document.getElementById('patternPreviewPanel');
  992. const layoutContainer = document.querySelector('.layout-content-container');
  993. previewPanel.classList.add('translate-x-full');
  994. if (window.innerWidth >= 1024) {
  995. previewPanel.classList.add('lg:opacity-0', 'lg:pointer-events-none');
  996. }
  997. layoutContainer.parentElement.classList.remove('preview-open');
  998. // Clear the preview panel content
  999. document.getElementById('patternPreviewImage').src = '';
  1000. document.getElementById('patternPreviewTitle').textContent = 'Pattern Details';
  1001. document.getElementById('firstCoordinate').textContent = '(0, 0)';
  1002. document.getElementById('lastCoordinate').textContent = '(0, 0)';
  1003. // Refresh the pattern list (cache already invalidated above)
  1004. await loadPatterns();
  1005. } else {
  1006. throw new Error(result.error || 'Unknown error');
  1007. }
  1008. } catch (error) {
  1009. logMessage(`Failed to delete pattern: ${error.message}`, LOG_TYPE.ERROR);
  1010. showStatusMessage(`Failed to delete pattern: ${error.message}`, 'error');
  1011. }
  1012. }
  1013. };
  1014. // Handle pre-execution action changes
  1015. preExecutionInputs.forEach(input => {
  1016. input.onchange = () => {
  1017. const action = input.parentElement.textContent.trim();
  1018. logMessage(`Pre-execution action changed to: ${action}`, LOG_TYPE.INFO);
  1019. };
  1020. });
  1021. }
  1022. // Search patterns
  1023. // Sort patterns by specified field and direction
  1024. function sortPatterns(patterns, sortField, sortDirection) {
  1025. return patterns.sort((a, b) => {
  1026. let aVal, bVal;
  1027. switch (sortField) {
  1028. case 'name':
  1029. aVal = a.name.toLowerCase();
  1030. bVal = b.name.toLowerCase();
  1031. break;
  1032. case 'date':
  1033. aVal = a.date_modified;
  1034. bVal = b.date_modified;
  1035. break;
  1036. case 'coordinates':
  1037. aVal = a.coordinates_count;
  1038. bVal = b.coordinates_count;
  1039. break;
  1040. case 'favorite':
  1041. // Sort by favorite status first, then by name as secondary sort
  1042. const aIsFavorite = favoritePatterns.has(a.path);
  1043. const bIsFavorite = favoritePatterns.has(b.path);
  1044. if (aIsFavorite && !bIsFavorite) return sortDirection === 'asc' ? -1 : 1;
  1045. if (!aIsFavorite && bIsFavorite) return sortDirection === 'asc' ? 1 : -1;
  1046. // Both have same favorite status, sort by name as secondary sort
  1047. aVal = a.name.toLowerCase();
  1048. bVal = b.name.toLowerCase();
  1049. break;
  1050. default:
  1051. aVal = a.name.toLowerCase();
  1052. bVal = b.name.toLowerCase();
  1053. }
  1054. let result = 0;
  1055. if (aVal < bVal) result = -1;
  1056. else if (aVal > bVal) result = 1;
  1057. return sortDirection === 'asc' ? result : -result;
  1058. });
  1059. }
  1060. // Filter patterns based on current filters
  1061. function filterPatterns(patterns, filters, searchQuery = '') {
  1062. return patterns.filter(pattern => {
  1063. // Category filter
  1064. if (filters.category !== 'all' && pattern.category !== filters.category) {
  1065. return false;
  1066. }
  1067. // Search query filter
  1068. if (searchQuery.trim()) {
  1069. const normalizedQuery = searchQuery.toLowerCase().trim();
  1070. const patternName = pattern.name.toLowerCase();
  1071. const category = pattern.category.toLowerCase();
  1072. return patternName.includes(normalizedQuery) || category.includes(normalizedQuery);
  1073. }
  1074. return true;
  1075. });
  1076. }
  1077. // Apply sorting and filtering to patterns
  1078. function applyPatternsFilteringAndSorting() {
  1079. const searchQuery = document.getElementById('patternSearch')?.value || '';
  1080. // Check if enhanced metadata is available
  1081. if (!allPatternsWithMetadata || allPatternsWithMetadata.length === 0) {
  1082. // Fallback to basic search if metadata not loaded yet
  1083. if (searchQuery.trim()) {
  1084. const filteredPatterns = allPatterns.filter(pattern =>
  1085. pattern.toLowerCase().includes(searchQuery.toLowerCase())
  1086. );
  1087. displayFilteredPatterns(filteredPatterns);
  1088. } else {
  1089. // Just display current batch if no search
  1090. displayPatternBatch();
  1091. }
  1092. return;
  1093. }
  1094. // Start with all available patterns with metadata
  1095. let patterns = [...allPatternsWithMetadata];
  1096. // Apply filters
  1097. patterns = filterPatterns(patterns, currentFilters, searchQuery);
  1098. // Apply sorting
  1099. patterns = sortPatterns(patterns, currentSort.field, currentSort.direction);
  1100. // Update filtered patterns (convert back to path format for compatibility)
  1101. const filteredPatterns = patterns.map(p => p.path);
  1102. // Display filtered patterns
  1103. displayFilteredPatterns(filteredPatterns);
  1104. updateBrowseSortAndFilterUI();
  1105. }
  1106. // Display filtered patterns
  1107. function displayFilteredPatterns(filteredPatterns) {
  1108. const patternGrid = document.querySelector('.grid');
  1109. if (!patternGrid) return;
  1110. patternGrid.innerHTML = '';
  1111. if (filteredPatterns.length === 0) {
  1112. patternGrid.innerHTML = '<div class="col-span-full text-center text-gray-500 py-8">No patterns found</div>';
  1113. return;
  1114. }
  1115. filteredPatterns.forEach(pattern => {
  1116. const patternCard = createPatternCard(pattern);
  1117. patternGrid.appendChild(patternCard);
  1118. });
  1119. // Give the browser a chance to render the cards
  1120. requestAnimationFrame(() => {
  1121. // Trigger preview loading for the search results
  1122. triggerPreviewLoadingForVisible();
  1123. });
  1124. logMessage(`Displaying ${filteredPatterns.length} patterns`, LOG_TYPE.INFO);
  1125. }
  1126. function searchPatterns(query) {
  1127. // Update the search input if called programmatically
  1128. const searchInput = document.getElementById('patternSearch');
  1129. if (searchInput && searchInput.value !== query) {
  1130. searchInput.value = query;
  1131. }
  1132. applyPatternsFilteringAndSorting();
  1133. }
  1134. // Update sort and filter UI to reflect current state
  1135. function updateBrowseSortAndFilterUI() {
  1136. // Update sort direction icon
  1137. const sortDirectionIcon = document.getElementById('browseSortDirectionIcon');
  1138. if (sortDirectionIcon) {
  1139. sortDirectionIcon.textContent = currentSort.direction === 'asc' ? 'arrow_upward' : 'arrow_downward';
  1140. }
  1141. // Update sort field select
  1142. const sortFieldSelect = document.getElementById('browseSortFieldSelect');
  1143. if (sortFieldSelect) {
  1144. sortFieldSelect.value = currentSort.field;
  1145. }
  1146. // Update filter selects
  1147. const categorySelect = document.getElementById('browseCategoryFilterSelect');
  1148. if (categorySelect) {
  1149. categorySelect.value = currentFilters.category;
  1150. }
  1151. }
  1152. // Populate category filter dropdown with available categories (subfolders)
  1153. function updateBrowseCategoryFilter() {
  1154. const categorySelect = document.getElementById('browseCategoryFilterSelect');
  1155. if (!categorySelect) return;
  1156. // Check if metadata is available
  1157. if (!allPatternsWithMetadata || allPatternsWithMetadata.length === 0) {
  1158. // Show basic options if metadata not loaded
  1159. categorySelect.innerHTML = '<option value="all">All Folders (loading...)</option>';
  1160. return;
  1161. }
  1162. // Get unique categories (subfolders)
  1163. const categories = [...new Set(allPatternsWithMetadata.map(p => p.category))].sort();
  1164. // Clear existing options except "All"
  1165. categorySelect.innerHTML = '<option value="all">All Folders</option>';
  1166. // Add category options
  1167. categories.forEach(category => {
  1168. if (category) {
  1169. const option = document.createElement('option');
  1170. option.value = category;
  1171. // Display friendly names for full paths
  1172. if (category === 'root') {
  1173. option.textContent = 'Root Folder';
  1174. } else {
  1175. // For full paths, show the path but make it more readable
  1176. const parts = category
  1177. .split('/')
  1178. .map(part => part.charAt(0).toUpperCase() + part.slice(1).replace('_', ' '));
  1179. // Check if we're on a small screen and truncate if necessary
  1180. const isSmallScreen = window.innerWidth < 640; // sm breakpoint
  1181. let displayName;
  1182. if (isSmallScreen && parts.length > 1) {
  1183. // On small screens, show only the last part with "..." if nested
  1184. displayName = '...' + parts[parts.length - 1];
  1185. } else {
  1186. // Full path with separators
  1187. displayName = parts.join(' › ');
  1188. }
  1189. option.textContent = displayName;
  1190. }
  1191. categorySelect.appendChild(option);
  1192. }
  1193. });
  1194. }
  1195. // Handle sort field change
  1196. function handleBrowseSortFieldChange() {
  1197. const sortFieldSelect = document.getElementById('browseSortFieldSelect');
  1198. if (sortFieldSelect) {
  1199. currentSort.field = sortFieldSelect.value;
  1200. applyPatternsFilteringAndSorting();
  1201. }
  1202. }
  1203. // Handle sort direction toggle
  1204. function handleBrowseSortDirectionToggle() {
  1205. currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
  1206. applyPatternsFilteringAndSorting();
  1207. }
  1208. // Handle category filter change
  1209. function handleBrowseCategoryFilterChange() {
  1210. const categorySelect = document.getElementById('browseCategoryFilterSelect');
  1211. if (categorySelect) {
  1212. currentFilters.category = categorySelect.value;
  1213. applyPatternsFilteringAndSorting();
  1214. }
  1215. }
  1216. // Enable sort controls when metadata is loaded
  1217. function enableSortControls() {
  1218. const browseSortFieldSelect = document.getElementById('browseSortFieldSelect');
  1219. const browseSortDirectionBtn = document.getElementById('browseSortDirectionBtn');
  1220. const browseCategoryFilterSelect = document.getElementById('browseCategoryFilterSelect');
  1221. if (browseSortFieldSelect) {
  1222. browseSortFieldSelect.disabled = false;
  1223. // Ensure dropdown shows the current sort field
  1224. browseSortFieldSelect.value = currentSort.field;
  1225. }
  1226. if (browseSortDirectionBtn) {
  1227. browseSortDirectionBtn.disabled = false;
  1228. browseSortDirectionBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  1229. browseSortDirectionBtn.classList.add('hover:bg-gray-200');
  1230. browseSortDirectionBtn.title = 'Toggle sort direction';
  1231. // Update direction icon
  1232. const sortDirectionIcon = document.getElementById('browseSortDirectionIcon');
  1233. if (sortDirectionIcon) {
  1234. sortDirectionIcon.textContent = currentSort.direction === 'asc' ? 'arrow_upward' : 'arrow_downward';
  1235. }
  1236. }
  1237. if (browseCategoryFilterSelect) {
  1238. browseCategoryFilterSelect.disabled = false;
  1239. }
  1240. // Only apply sorting if user has changed from defaults or if patterns need to be refreshed
  1241. // If already showing patterns with default sort (name, asc), don't reorder unnecessarily
  1242. if (currentSort.field !== 'name' || currentSort.direction !== 'asc' || currentFilters.category !== 'all') {
  1243. applyPatternsFilteringAndSorting();
  1244. }
  1245. }
  1246. // Filter patterns by category
  1247. function filterPatternsByCategory(category) {
  1248. // TODO: Implement category filtering logic
  1249. logMessage(`Filtering patterns by category: ${category}`, LOG_TYPE.INFO);
  1250. }
  1251. // Filter patterns by tag
  1252. function filterPatternsByTag(tag) {
  1253. // TODO: Implement tag filtering logic
  1254. logMessage(`Filtering patterns by tag: ${tag}`, LOG_TYPE.INFO);
  1255. }
  1256. // Initialize the patterns page
  1257. document.addEventListener('DOMContentLoaded', async () => {
  1258. try {
  1259. logMessage('Initializing patterns page...', LOG_TYPE.DEBUG);
  1260. // Initialize IndexedDB preview cache (shared with playlists page)
  1261. await initPreviewCacheDB();
  1262. // Setup upload event handlers
  1263. setupUploadEventHandlers();
  1264. // Initialize intersection observer for lazy loading
  1265. initPreviewObserver();
  1266. // Setup search functionality
  1267. const searchInput = document.getElementById('patternSearch');
  1268. const searchButton = document.getElementById('searchButton');
  1269. const cacheAllButton = document.getElementById('cacheAllButton');
  1270. if (searchInput && searchButton) {
  1271. // Search on button click
  1272. searchButton.addEventListener('click', () => {
  1273. searchPatterns(searchInput.value.trim());
  1274. });
  1275. // Search on Enter key
  1276. searchInput.addEventListener('keypress', (e) => {
  1277. if (e.key === 'Enter') {
  1278. searchPatterns(searchInput.value.trim());
  1279. }
  1280. });
  1281. // Clear search when input is empty
  1282. searchInput.addEventListener('input', (e) => {
  1283. if (e.target.value.trim() === '') {
  1284. searchPatterns('');
  1285. }
  1286. });
  1287. }
  1288. // Sort and filter controls for browse page
  1289. const browseSortFieldSelect = document.getElementById('browseSortFieldSelect');
  1290. const browseSortDirectionBtn = document.getElementById('browseSortDirectionBtn');
  1291. const browseCategoryFilterSelect = document.getElementById('browseCategoryFilterSelect');
  1292. if (browseSortFieldSelect) {
  1293. browseSortFieldSelect.addEventListener('change', handleBrowseSortFieldChange);
  1294. }
  1295. if (browseSortDirectionBtn) {
  1296. browseSortDirectionBtn.addEventListener('click', handleBrowseSortDirectionToggle);
  1297. }
  1298. if (browseCategoryFilterSelect) {
  1299. browseCategoryFilterSelect.addEventListener('change', handleBrowseCategoryFilterChange);
  1300. }
  1301. // Setup cache all button - now triggers the modal
  1302. if (cacheAllButton) {
  1303. cacheAllButton.addEventListener('click', () => {
  1304. // Always show the modal when manually clicked, using forceShow parameter
  1305. if (typeof showCacheAllPrompt === 'function') {
  1306. showCacheAllPrompt(true); // true = forceShow
  1307. } else {
  1308. // Fallback if function not available
  1309. const modal = document.getElementById('cacheAllPromptModal');
  1310. if (modal) {
  1311. modal.classList.remove('hidden');
  1312. modal.dataset.manuallyTriggered = 'true';
  1313. }
  1314. }
  1315. });
  1316. }
  1317. // Load favorites first, then patterns
  1318. await loadFavorites();
  1319. await loadPatterns();
  1320. logMessage('Patterns page initialized successfully', LOG_TYPE.SUCCESS);
  1321. } catch (error) {
  1322. logMessage(`Error during initialization: ${error.message}`, LOG_TYPE.ERROR);
  1323. }
  1324. });
  1325. // Cancel any pending requests when navigating away from the page
  1326. window.addEventListener('beforeunload', () => {
  1327. if (metadataAbortController) {
  1328. metadataAbortController.abort();
  1329. metadataAbortController = null;
  1330. logMessage('Cancelled pending metadata request due to navigation', LOG_TYPE.DEBUG);
  1331. }
  1332. });
  1333. // Also handle page visibility changes (switching tabs, minimizing, etc.)
  1334. document.addEventListener('visibilitychange', () => {
  1335. if (document.hidden && metadataAbortController) {
  1336. // Cancel long-running requests when page is hidden
  1337. metadataAbortController.abort();
  1338. metadataAbortController = null;
  1339. logMessage('Cancelled pending metadata request due to page hidden', LOG_TYPE.DEBUG);
  1340. }
  1341. });
  1342. function updateCurrentlyPlayingUI(status) {
  1343. // Get all required DOM elements once
  1344. const container = document.getElementById('currently-playing-container');
  1345. const fileNameElement = document.getElementById('currently-playing-file');
  1346. const progressBar = document.getElementById('play_progress');
  1347. const progressText = document.getElementById('play_progress_text');
  1348. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1349. const speedDisplay = document.getElementById('current_speed_display');
  1350. const speedInput = document.getElementById('speedInput');
  1351. // Check if all required elements exist
  1352. if (!container || !fileNameElement || !progressBar || !progressText) {
  1353. console.log('Required DOM elements not found:', {
  1354. container: !!container,
  1355. fileNameElement: !!fileNameElement,
  1356. progressBar: !!progressBar,
  1357. progressText: !!progressText
  1358. });
  1359. setTimeout(() => updateCurrentlyPlayingUI(status), 100);
  1360. return;
  1361. }
  1362. // Update container visibility based on status
  1363. if (status.current_file && status.is_running) {
  1364. document.body.classList.add('playing');
  1365. container.style.display = 'flex';
  1366. } else {
  1367. document.body.classList.remove('playing');
  1368. container.style.display = 'none';
  1369. }
  1370. // Update file name display
  1371. if (status.current_file) {
  1372. const fileName = normalizeFilePath(status.current_file);
  1373. fileNameElement.textContent = fileName;
  1374. } else {
  1375. fileNameElement.textContent = 'No pattern playing';
  1376. }
  1377. // Update next file display
  1378. const nextFileElement = document.getElementById('next-file');
  1379. if (nextFileElement) {
  1380. if (status.playlist && status.playlist.next_file) {
  1381. const nextFileName = normalizeFilePath(status.playlist.next_file);
  1382. nextFileElement.textContent = `(Next: ${nextFileName})`;
  1383. nextFileElement.style.display = 'block';
  1384. } else {
  1385. nextFileElement.style.display = 'none';
  1386. }
  1387. }
  1388. // Update speed display and input if they exist
  1389. if (status.speed) {
  1390. if (speedDisplay) {
  1391. speedDisplay.textContent = `Current Speed: ${status.speed}`;
  1392. }
  1393. if (speedInput) {
  1394. speedInput.value = status.speed;
  1395. }
  1396. }
  1397. // Update pattern preview if it's a new pattern
  1398. // ... existing code ...
  1399. }
  1400. // Setup upload event handlers
  1401. function setupUploadEventHandlers() {
  1402. // Upload file input handler - supports multiple files
  1403. document.getElementById('patternFileInput').addEventListener('change', async function(e) {
  1404. const files = e.target.files;
  1405. if (!files || files.length === 0) return;
  1406. const totalFiles = files.length;
  1407. const fileArray = Array.from(files);
  1408. let successCount = 0;
  1409. let failCount = 0;
  1410. // Show initial progress message
  1411. showStatusMessage(`Uploading ${totalFiles} pattern${totalFiles > 1 ? 's' : ''}...`);
  1412. try {
  1413. // Upload files sequentially to avoid overwhelming the server
  1414. for (let i = 0; i < fileArray.length; i++) {
  1415. const file = fileArray[i];
  1416. try {
  1417. const formData = new FormData();
  1418. formData.append('file', file);
  1419. const response = await fetch('/upload_theta_rho', {
  1420. method: 'POST',
  1421. body: formData
  1422. });
  1423. const result = await response.json();
  1424. if (result.success) {
  1425. successCount++;
  1426. // Invalidate pattern files cache to include new file
  1427. invalidatePatternFilesCache();
  1428. // Clear any existing cache for this pattern to ensure fresh loading
  1429. const newPatternPath = `custom_patterns/${file.name}`;
  1430. previewCache.delete(newPatternPath);
  1431. logMessage(`Successfully uploaded: ${file.name}`, LOG_TYPE.SUCCESS);
  1432. } else {
  1433. failCount++;
  1434. logMessage(`Failed to upload ${file.name}: ${result.error}`, LOG_TYPE.ERROR);
  1435. }
  1436. } catch (fileError) {
  1437. failCount++;
  1438. logMessage(`Error uploading ${file.name}: ${fileError.message}`, LOG_TYPE.ERROR);
  1439. }
  1440. // Update progress
  1441. const progress = i + 1;
  1442. showStatusMessage(`Uploading patterns... ${progress}/${totalFiles}`);
  1443. }
  1444. // Show final result
  1445. if (successCount > 0) {
  1446. const message = failCount > 0
  1447. ? `Uploaded ${successCount} pattern${successCount > 1 ? 's' : ''}, ${failCount} failed`
  1448. : `Successfully uploaded ${successCount} pattern${successCount > 1 ? 's' : ''}`;
  1449. showStatusMessage(message);
  1450. // Add a small delay to allow backend preview generation to complete
  1451. await new Promise(resolve => setTimeout(resolve, 1000));
  1452. // Refresh the pattern list (cache already invalidated above)
  1453. await loadPatterns();
  1454. // Trigger preview loading for newly uploaded patterns
  1455. setTimeout(() => {
  1456. fileArray.forEach(file => {
  1457. const newPatternPath = `custom_patterns/${file.name}`;
  1458. const newPatternCard = document.querySelector(`[data-pattern="${newPatternPath}"]`);
  1459. if (newPatternCard) {
  1460. const previewContainer = newPatternCard.querySelector('.pattern-preview');
  1461. if (previewContainer) {
  1462. previewContainer.dataset.retryCount = '0';
  1463. previewContainer.dataset.hasTriedIndividual = 'false';
  1464. previewContainer.dataset.isNewUpload = 'true';
  1465. addPatternToBatch(newPatternPath, previewContainer);
  1466. }
  1467. }
  1468. });
  1469. }, 500);
  1470. } else {
  1471. showStatusMessage(`Failed to upload all ${totalFiles} pattern${totalFiles > 1 ? 's' : ''}`, 'error');
  1472. }
  1473. // Clear the file input
  1474. e.target.value = '';
  1475. } catch (error) {
  1476. console.error('Error during batch upload:', error);
  1477. showStatusMessage(`Error uploading patterns: ${error.message}`, 'error');
  1478. }
  1479. });
  1480. // Pattern deletion handler
  1481. const deleteModal = document.getElementById('deleteConfirmModal');
  1482. if (deleteModal) {
  1483. const confirmBtn = deleteModal.querySelector('#confirmDeleteBtn');
  1484. const cancelBtn = deleteModal.querySelector('#cancelDeleteBtn');
  1485. if (confirmBtn) {
  1486. confirmBtn.addEventListener('click', async () => {
  1487. const patternToDelete = confirmBtn.dataset.pattern;
  1488. if (patternToDelete) {
  1489. await deletePattern(patternToDelete);
  1490. // Refresh after deletion (cache invalidated in deletePattern)
  1491. await loadPatterns();
  1492. }
  1493. deleteModal.classList.add('hidden');
  1494. });
  1495. }
  1496. if (cancelBtn) {
  1497. cancelBtn.addEventListener('click', () => {
  1498. deleteModal.classList.add('hidden');
  1499. });
  1500. }
  1501. }
  1502. }
  1503. // Cache all pattern previews
  1504. async function cacheAllPreviews() {
  1505. const cacheAllButton = document.getElementById('cacheAllButton');
  1506. if (!cacheAllButton) return;
  1507. try {
  1508. // Disable button and show loading state
  1509. cacheAllButton.disabled = true;
  1510. // Get current cache size
  1511. const currentSize = await getPreviewCacheSize();
  1512. const maxSize = MAX_CACHE_SIZE_BYTES || (200 * 1024 * 1024); // 200MB default
  1513. if (currentSize > maxSize) {
  1514. // Clear cache if it's too large
  1515. await clearPreviewCache();
  1516. // Also clear progress since we're starting fresh
  1517. localStorage.removeItem(CACHE_PROGRESS_KEY);
  1518. localStorage.removeItem(CACHE_TIMESTAMP_KEY);
  1519. }
  1520. // Get all patterns that aren't cached yet
  1521. const uncachedPatterns = allPatterns.filter(pattern => !previewCache.has(pattern));
  1522. if (uncachedPatterns.length === 0) {
  1523. showStatusMessage('All patterns are already cached!', 'info');
  1524. return;
  1525. }
  1526. // Check for existing progress
  1527. let startIndex = 0;
  1528. const savedProgress = localStorage.getItem(CACHE_PROGRESS_KEY);
  1529. const savedTimestamp = localStorage.getItem(CACHE_TIMESTAMP_KEY);
  1530. if (savedProgress && savedTimestamp) {
  1531. const progressAge = Date.now() - parseInt(savedTimestamp);
  1532. if (progressAge < CACHE_PROGRESS_EXPIRY) {
  1533. const lastCachedPattern = savedProgress;
  1534. const lastIndex = uncachedPatterns.findIndex(p => p === lastCachedPattern);
  1535. if (lastIndex !== -1) {
  1536. startIndex = lastIndex + 1;
  1537. showStatusMessage('Resuming from previous progress...', 'info');
  1538. }
  1539. } else {
  1540. // Clear expired progress
  1541. localStorage.removeItem(CACHE_PROGRESS_KEY);
  1542. localStorage.removeItem(CACHE_TIMESTAMP_KEY);
  1543. }
  1544. }
  1545. // Process patterns in smaller batches to avoid overwhelming the server
  1546. const BATCH_SIZE = 10;
  1547. const remainingPatterns = uncachedPatterns.slice(startIndex);
  1548. const totalBatches = Math.ceil(remainingPatterns.length / BATCH_SIZE);
  1549. for (let i = 0; i < totalBatches; i++) {
  1550. const batchStart = i * BATCH_SIZE;
  1551. const batchEnd = Math.min(batchStart + BATCH_SIZE, remainingPatterns.length);
  1552. const batchPatterns = remainingPatterns.slice(batchStart, batchEnd);
  1553. // Update button text with progress
  1554. const overallProgress = Math.round(((startIndex + batchStart + BATCH_SIZE) / uncachedPatterns.length) * 100);
  1555. cacheAllButton.innerHTML = `
  1556. <div class="bg-white bg-opacity-30 rounded-full h-4 w-4 flex items-center justify-center">
  1557. <div class="bg-white rounded-full h-2 w-2"></div>
  1558. </div>
  1559. <span>Caching ${overallProgress}%</span>
  1560. `;
  1561. try {
  1562. const response = await fetch('/preview_thr_batch', {
  1563. method: 'POST',
  1564. headers: { 'Content-Type': 'application/json' },
  1565. body: JSON.stringify({ file_names: batchPatterns })
  1566. });
  1567. if (response.ok) {
  1568. const results = await response.json();
  1569. // Cache each preview
  1570. for (const [pattern, data] of Object.entries(results)) {
  1571. if (data && !data.error && data.image_data) {
  1572. previewCache.set(pattern, data);
  1573. await savePreviewToCache(pattern, data);
  1574. // Save progress after each successful pattern
  1575. localStorage.setItem(CACHE_PROGRESS_KEY, pattern);
  1576. localStorage.setItem(CACHE_TIMESTAMP_KEY, Date.now().toString());
  1577. }
  1578. }
  1579. }
  1580. } catch (error) {
  1581. logMessage(`Error caching batch ${i + 1}: ${error.message}`, LOG_TYPE.ERROR);
  1582. // Don't clear progress on error - allows resuming from last successful pattern
  1583. }
  1584. // Small delay between batches to prevent overwhelming the server
  1585. await new Promise(resolve => setTimeout(resolve, 100));
  1586. }
  1587. // Clear progress after successful completion
  1588. localStorage.removeItem(CACHE_PROGRESS_KEY);
  1589. localStorage.removeItem(CACHE_TIMESTAMP_KEY);
  1590. // Show success message
  1591. showStatusMessage('All pattern previews have been cached!', 'success');
  1592. } catch (error) {
  1593. logMessage(`Error caching previews: ${error.message}`, LOG_TYPE.ERROR);
  1594. showStatusMessage('Failed to cache all previews. Click again to resume.', 'error');
  1595. } finally {
  1596. // Reset button state
  1597. if (cacheAllButton) {
  1598. cacheAllButton.disabled = false;
  1599. cacheAllButton.innerHTML = `
  1600. <span class="material-icons text-sm">cached</span>
  1601. Cache All Previews
  1602. `;
  1603. }
  1604. }
  1605. }
  1606. // Open animated preview modal
  1607. async function openAnimatedPreview(pattern) {
  1608. try {
  1609. const modal = document.getElementById('animatedPreviewModal');
  1610. const title = document.getElementById('animatedPreviewTitle');
  1611. const canvas = document.getElementById('animatedPreviewCanvas');
  1612. const ctx = canvas.getContext('2d');
  1613. // Set title
  1614. title.textContent = pattern.replace('.thr', '').split('/').pop();
  1615. // Show modal
  1616. modal.classList.remove('hidden');
  1617. // Load pattern coordinates
  1618. const response = await fetch('/get_theta_rho_coordinates', {
  1619. method: 'POST',
  1620. headers: { 'Content-Type': 'application/json' },
  1621. body: JSON.stringify({ file_name: pattern })
  1622. });
  1623. if (!response.ok) {
  1624. throw new Error(`HTTP error! status: ${response.status}`);
  1625. }
  1626. const data = await response.json();
  1627. if (data.error) {
  1628. throw new Error(data.error);
  1629. }
  1630. animatedPreviewData = data.coordinates;
  1631. // Setup canvas
  1632. setupAnimatedPreviewCanvas(ctx);
  1633. // Setup controls
  1634. setupAnimatedPreviewControls();
  1635. // Draw initial state
  1636. drawAnimatedPreview(ctx, 0);
  1637. // Auto-play the animation
  1638. setTimeout(() => {
  1639. playAnimation();
  1640. }, 100); // Small delay to ensure everything is set up
  1641. } catch (error) {
  1642. logMessage(`Error opening animated preview: ${error.message}`, LOG_TYPE.ERROR);
  1643. showStatusMessage('Failed to load pattern for animation', 'error');
  1644. }
  1645. }
  1646. // Setup animated preview canvas
  1647. function setupAnimatedPreviewCanvas(ctx) {
  1648. const canvas = ctx.canvas;
  1649. const size = canvas.width;
  1650. const center = size / 2;
  1651. const scale = (size / 2) - 30; // Slightly smaller to account for border
  1652. // Clear canvas with white background
  1653. ctx.fillStyle = '#ffffff';
  1654. ctx.fillRect(0, 0, size, size);
  1655. // Set drawing style for ultra-high quality lines
  1656. ctx.strokeStyle = '#000000';
  1657. ctx.lineWidth = 1; // Thinner line for higher resolution
  1658. ctx.lineCap = 'round';
  1659. ctx.lineJoin = 'round';
  1660. // Enable high quality rendering
  1661. ctx.imageSmoothingEnabled = true;
  1662. ctx.imageSmoothingQuality = 'high';
  1663. }
  1664. // Setup animated preview controls
  1665. function setupAnimatedPreviewControls() {
  1666. const modal = document.getElementById('animatedPreviewModal');
  1667. const closeBtn = document.getElementById('closeAnimatedPreview');
  1668. const playPauseBtn = document.getElementById('playPauseBtn');
  1669. const resetBtn = document.getElementById('resetBtn');
  1670. const speedSlider = document.getElementById('speedSlider');
  1671. const speedValue = document.getElementById('speedValue');
  1672. const progressSlider = document.getElementById('progressSlider');
  1673. const progressValue = document.getElementById('progressValue');
  1674. const canvas = document.getElementById('animatedPreviewCanvas');
  1675. const playPauseOverlay = document.getElementById('playPauseOverlay');
  1676. // Set responsive canvas size with ultra-high-DPI support
  1677. const setCanvasSize = () => {
  1678. const container = canvas.parentElement;
  1679. const modal = document.getElementById('animatedPreviewModal');
  1680. if (!container || !modal) return;
  1681. // Calculate available viewport space
  1682. const viewportWidth = window.innerWidth;
  1683. const viewportHeight = window.innerHeight;
  1684. // Calculate modal content area (95vh max height - header - padding)
  1685. const modalMaxHeight = viewportHeight * 0.95;
  1686. const headerHeight = 80; // Approximate header height with padding
  1687. const modalPadding = 48; // Modal padding (p-6 = 24px each side)
  1688. const availableHeight = modalMaxHeight - headerHeight - modalPadding;
  1689. // Calculate available width (max-w-4xl = 896px, but respect viewport)
  1690. const modalMaxWidth = Math.min(896, viewportWidth - 32); // Account for modal margin
  1691. const availableWidth = modalMaxWidth - modalPadding;
  1692. // Calculate ideal canvas size (use 80% of available space as requested)
  1693. const targetHeight = availableHeight * 0.8;
  1694. const targetWidth = availableWidth * 0.8;
  1695. // Use the smaller dimension to maintain square aspect ratio
  1696. let idealSize = Math.min(targetWidth, targetHeight);
  1697. // Cap at reasonable maximum and minimum
  1698. idealSize = Math.min(idealSize, 800); // Maximum size cap
  1699. idealSize = Math.max(idealSize, 200); // Minimum size
  1700. const displaySize = idealSize;
  1701. console.log('Canvas sizing:', {
  1702. viewport: `${viewportWidth}x${viewportHeight}`,
  1703. availableModal: `${availableWidth}x${availableHeight}`,
  1704. target80pct: `${targetWidth}x${targetHeight}`,
  1705. finalSize: displaySize
  1706. });
  1707. // Get device pixel ratio and multiply by 2 for higher resolution
  1708. const pixelRatio = (window.devicePixelRatio || 1) * 2;
  1709. // Set the display size (CSS pixels) - use pixels, not percentage
  1710. canvas.style.width = displaySize + 'px';
  1711. canvas.style.height = displaySize + 'px';
  1712. // Set the actual canvas size (device pixels) - increased resolution
  1713. canvas.width = displaySize * pixelRatio;
  1714. canvas.height = displaySize * pixelRatio;
  1715. // Scale the context to match the increased pixel ratio
  1716. const ctx = canvas.getContext('2d', { alpha: false }); // Disable alpha for better performance
  1717. ctx.scale(pixelRatio, pixelRatio);
  1718. // Enable high quality rendering
  1719. ctx.imageSmoothingEnabled = true;
  1720. ctx.imageSmoothingQuality = 'high';
  1721. // Redraw with new size
  1722. if (animatedPreviewData) {
  1723. setupAnimatedPreviewCanvas(ctx);
  1724. drawAnimatedPreview(ctx, currentProgress / 100);
  1725. }
  1726. };
  1727. // Set initial size
  1728. setCanvasSize();
  1729. // Handle window resize with debouncing
  1730. let resizeTimeout;
  1731. window.addEventListener('resize', () => {
  1732. clearTimeout(resizeTimeout);
  1733. resizeTimeout = setTimeout(setCanvasSize, 16); // ~60fps update rate
  1734. });
  1735. // Close modal
  1736. closeBtn.onclick = closeAnimatedPreview;
  1737. modal.onclick = (e) => {
  1738. if (e.target === modal) closeAnimatedPreview();
  1739. };
  1740. // Play/Pause button
  1741. playPauseBtn.onclick = toggleAnimation;
  1742. // Reset button
  1743. resetBtn.onclick = resetAnimation;
  1744. // Speed slider
  1745. speedSlider.oninput = (e) => {
  1746. animationSpeed = parseFloat(e.target.value);
  1747. speedValue.textContent = `${animationSpeed}x`;
  1748. };
  1749. // Progress slider
  1750. progressSlider.oninput = (e) => {
  1751. currentProgress = parseFloat(e.target.value);
  1752. progressValue.textContent = `${currentProgress.toFixed(1)}%`;
  1753. drawAnimatedPreview(canvas.getContext('2d'), currentProgress / 100);
  1754. if (isPlaying) {
  1755. // Pause animation when manually adjusting progress
  1756. toggleAnimation();
  1757. }
  1758. };
  1759. // Canvas click to play/pause
  1760. canvas.onclick = () => {
  1761. playPauseOverlay.style.opacity = '1';
  1762. setTimeout(() => {
  1763. playPauseOverlay.style.opacity = '0';
  1764. }, 200);
  1765. toggleAnimation();
  1766. };
  1767. // Keyboard shortcuts
  1768. document.addEventListener('keydown', (e) => {
  1769. if (modal.classList.contains('hidden')) return;
  1770. switch(e.code) {
  1771. case 'Space':
  1772. e.preventDefault();
  1773. toggleAnimation();
  1774. break;
  1775. case 'Escape':
  1776. closeAnimatedPreview();
  1777. break;
  1778. case 'ArrowLeft':
  1779. e.preventDefault();
  1780. currentProgress = Math.max(0, currentProgress - 5);
  1781. updateProgressUI();
  1782. drawAnimatedPreview(canvas.getContext('2d'), currentProgress / 100);
  1783. break;
  1784. case 'ArrowRight':
  1785. e.preventDefault();
  1786. currentProgress = Math.min(100, currentProgress + 5);
  1787. updateProgressUI();
  1788. drawAnimatedPreview(canvas.getContext('2d'), currentProgress / 100);
  1789. break;
  1790. }
  1791. });
  1792. }
  1793. // Draw animated preview
  1794. function drawAnimatedPreview(ctx, progress) {
  1795. if (!animatedPreviewData || animatedPreviewData.length === 0) return;
  1796. const canvas = ctx.canvas;
  1797. const pixelRatio = (window.devicePixelRatio || 1) * 2; // Match the increased ratio
  1798. const displayWidth = parseInt(canvas.style.width);
  1799. const displayHeight = parseInt(canvas.style.height);
  1800. const center = (canvas.width / pixelRatio) / 2;
  1801. const scale = ((canvas.width / pixelRatio) / 2) - 30;
  1802. // Clear canvas with white background
  1803. ctx.clearRect(0, 0, canvas.width, canvas.height);
  1804. // Calculate how many points to draw
  1805. const totalPoints = animatedPreviewData.length;
  1806. const pointsToDraw = Math.floor(totalPoints * progress);
  1807. if (pointsToDraw < 2) return;
  1808. // Draw the path with ultra-high quality settings
  1809. ctx.beginPath();
  1810. ctx.strokeStyle = '#000000';
  1811. ctx.lineWidth = 1; // Thinner line for higher resolution
  1812. ctx.lineCap = 'round';
  1813. ctx.lineJoin = 'round';
  1814. // Ensure sub-pixel alignment for ultra-high resolution
  1815. for (let i = 0; i < pointsToDraw; i++) {
  1816. const [theta, rho] = animatedPreviewData[i];
  1817. // Round to nearest 0.25 for even more precise lines
  1818. // Mirror both X and Y coordinates
  1819. const x = Math.round((center + rho * scale * Math.cos(theta)) * 4) / 4; // Changed minus to plus
  1820. const y = Math.round((center + rho * scale * Math.sin(theta)) * 4) / 4;
  1821. if (i === 0) {
  1822. ctx.moveTo(x, y);
  1823. } else {
  1824. ctx.lineTo(x, y);
  1825. }
  1826. }
  1827. ctx.stroke();
  1828. // Draw current position dot
  1829. if (pointsToDraw > 0) {
  1830. const [currentTheta, currentRho] = animatedPreviewData[pointsToDraw - 1];
  1831. const currentX = Math.round((center + currentRho * scale * Math.cos(currentTheta)) * 4) / 4; // Changed minus to plus
  1832. const currentY = Math.round((center + currentRho * scale * Math.sin(currentTheta)) * 4) / 4;
  1833. // Draw a filled circle at current position with anti-aliasing
  1834. ctx.fillStyle = '#ff4444'; // Red dot
  1835. ctx.beginPath();
  1836. ctx.arc(currentX, currentY, 6, 0, 2 * Math.PI); // Increased dot size
  1837. ctx.fill();
  1838. // Add a subtle white border
  1839. ctx.strokeStyle = '#ffffff';
  1840. ctx.lineWidth = 1.5;
  1841. ctx.stroke();
  1842. }
  1843. }
  1844. // Toggle animation play/pause
  1845. function toggleAnimation() {
  1846. if (isPlaying) {
  1847. pauseAnimation();
  1848. } else {
  1849. playAnimation();
  1850. }
  1851. }
  1852. // Play animation
  1853. function playAnimation() {
  1854. if (!animatedPreviewData) return;
  1855. isPlaying = true;
  1856. lastTimestamp = performance.now();
  1857. // Update UI
  1858. const playPauseBtn = document.getElementById('playPauseBtn');
  1859. const playPauseBtnIcon = document.getElementById('playPauseBtnIcon');
  1860. const playPauseBtnText = document.getElementById('playPauseBtnText');
  1861. if (playPauseBtnIcon) playPauseBtnIcon.textContent = 'pause';
  1862. if (playPauseBtnText) playPauseBtnText.textContent = 'Pause';
  1863. // Start animation loop
  1864. animationFrameId = requestAnimationFrame(animate);
  1865. }
  1866. // Pause animation
  1867. function pauseAnimation() {
  1868. isPlaying = false;
  1869. // Update UI
  1870. const playPauseBtn = document.getElementById('playPauseBtn');
  1871. const playPauseBtnIcon = document.getElementById('playPauseBtnIcon');
  1872. const playPauseBtnText = document.getElementById('playPauseBtnText');
  1873. if (playPauseBtnIcon) playPauseBtnIcon.textContent = 'play_arrow';
  1874. if (playPauseBtnText) playPauseBtnText.textContent = 'Play';
  1875. // Cancel animation frame
  1876. if (animationFrameId) {
  1877. cancelAnimationFrame(animationFrameId);
  1878. animationFrameId = null;
  1879. }
  1880. }
  1881. // Animation loop
  1882. function animate(timestamp) {
  1883. if (!isPlaying) return;
  1884. const deltaTime = timestamp - lastTimestamp;
  1885. const progressIncrement = (deltaTime / 1000) * animationSpeed * 2.0; // Much faster base speed
  1886. currentProgress = Math.min(100, currentProgress + progressIncrement);
  1887. // Update UI
  1888. updateProgressUI();
  1889. // Draw frame
  1890. const canvas = document.getElementById('animatedPreviewCanvas');
  1891. if (canvas) {
  1892. drawAnimatedPreview(canvas.getContext('2d'), currentProgress / 100);
  1893. }
  1894. // Continue animation
  1895. if (currentProgress < 100) {
  1896. lastTimestamp = timestamp;
  1897. animationFrameId = requestAnimationFrame(animate);
  1898. } else {
  1899. // Animation complete
  1900. pauseAnimation();
  1901. }
  1902. }
  1903. // Reset animation
  1904. function resetAnimation() {
  1905. pauseAnimation();
  1906. currentProgress = 0;
  1907. updateProgressUI();
  1908. const canvas = document.getElementById('animatedPreviewCanvas');
  1909. drawAnimatedPreview(canvas.getContext('2d'), 0);
  1910. }
  1911. // Update progress UI
  1912. function updateProgressUI() {
  1913. const progressSlider = document.getElementById('progressSlider');
  1914. const progressValue = document.getElementById('progressValue');
  1915. progressSlider.value = currentProgress;
  1916. progressValue.textContent = `${currentProgress.toFixed(1)}%`;
  1917. }
  1918. // Close animated preview
  1919. function closeAnimatedPreview() {
  1920. pauseAnimation();
  1921. const modal = document.getElementById('animatedPreviewModal');
  1922. modal.classList.add('hidden');
  1923. // Clear data
  1924. animatedPreviewData = null;
  1925. currentProgress = 0;
  1926. animationSpeed = 1;
  1927. // Reset UI
  1928. const speedSlider = document.getElementById('speedSlider');
  1929. const speedValue = document.getElementById('speedValue');
  1930. const progressSlider = document.getElementById('progressSlider');
  1931. const progressValue = document.getElementById('progressValue');
  1932. speedSlider.value = 1;
  1933. speedValue.textContent = '1x';
  1934. progressSlider.value = 0;
  1935. progressValue.textContent = '0%';
  1936. }
  1937. // Global set to track favorite patterns
  1938. let favoritePatterns = new Set();
  1939. // Make favoritePatterns available globally for other scripts
  1940. window.favoritePatterns = favoritePatterns;
  1941. // Load favorites from server on page load
  1942. async function loadFavorites() {
  1943. try {
  1944. const response = await fetch('/get_playlist?name=Favorites');
  1945. if (response.ok) {
  1946. const playlist = await response.json();
  1947. favoritePatterns = new Set(playlist.files);
  1948. window.favoritePatterns = favoritePatterns; // Keep window reference updated
  1949. updateAllHeartIcons();
  1950. }
  1951. } catch (error) {
  1952. // Favorites playlist doesn't exist yet - that's OK
  1953. console.debug('Favorites playlist not found, will create when needed');
  1954. }
  1955. }
  1956. // Toggle favorite status
  1957. async function toggleFavorite(pattern) {
  1958. const heartIcon = document.getElementById('heart-' + pattern.replace(/[^a-zA-Z0-9]/g, '_'));
  1959. if (!heartIcon) return;
  1960. try {
  1961. if (favoritePatterns.has(pattern)) {
  1962. // Remove from favorites
  1963. await removeFromFavorites(pattern);
  1964. favoritePatterns.delete(pattern);
  1965. heartIcon.textContent = 'favorite_border';
  1966. heartIcon.className = 'material-icons text-lg text-gray-400 hover:text-red-500 transition-colors';
  1967. // Make heart only visible on hover when not favorited
  1968. heartIcon.parentElement.className = heartIcon.parentElement.className.replace('opacity-100', 'opacity-0 group-hover:opacity-100');
  1969. showStatusMessage('Removed from favorites', 'success');
  1970. } else {
  1971. // Add to favorites
  1972. await addToFavorites(pattern);
  1973. favoritePatterns.add(pattern);
  1974. heartIcon.textContent = 'favorite';
  1975. heartIcon.className = 'material-icons text-lg text-red-500 hover:text-red-600 transition-colors';
  1976. // Make heart permanently visible when favorited
  1977. heartIcon.parentElement.className = heartIcon.parentElement.className.replace('opacity-0 group-hover:opacity-100', 'opacity-100');
  1978. showStatusMessage('Added to favorites', 'success');
  1979. }
  1980. } catch (error) {
  1981. console.error('Error toggling favorite:', error);
  1982. showStatusMessage('Failed to update favorites', 'error');
  1983. }
  1984. }
  1985. // Add pattern to favorites playlist
  1986. async function addToFavorites(pattern) {
  1987. try {
  1988. // First, check if Favorites playlist exists
  1989. const checkResponse = await fetch('/get_playlist?name=Favorites');
  1990. if (checkResponse.ok) {
  1991. // Playlist exists, add to it
  1992. const response = await fetch('/add_to_playlist', {
  1993. method: 'POST',
  1994. headers: {
  1995. 'Content-Type': 'application/json',
  1996. },
  1997. body: JSON.stringify({
  1998. playlist_name: 'Favorites',
  1999. pattern: pattern
  2000. })
  2001. });
  2002. if (!response.ok) {
  2003. throw new Error('Failed to add to favorites playlist');
  2004. }
  2005. } else {
  2006. // Playlist doesn't exist, create it with this pattern
  2007. const response = await fetch('/create_playlist', {
  2008. method: 'POST',
  2009. headers: {
  2010. 'Content-Type': 'application/json',
  2011. },
  2012. body: JSON.stringify({
  2013. playlist_name: 'Favorites',
  2014. files: [pattern]
  2015. })
  2016. });
  2017. if (!response.ok) {
  2018. throw new Error('Failed to create favorites playlist');
  2019. }
  2020. }
  2021. } catch (error) {
  2022. throw new Error(`Failed to add to favorites: ${error.message}`);
  2023. }
  2024. }
  2025. // Remove pattern from favorites playlist
  2026. async function removeFromFavorites(pattern) {
  2027. try {
  2028. // Get current favorites playlist
  2029. const getResponse = await fetch('/get_playlist?name=Favorites');
  2030. if (!getResponse.ok) return; // No favorites playlist
  2031. const currentFavorites = await getResponse.json();
  2032. const updatedFavorites = currentFavorites.files.filter(p => p !== pattern);
  2033. // Update the playlist
  2034. const updateResponse = await fetch('/modify_playlist', {
  2035. method: 'POST',
  2036. headers: {
  2037. 'Content-Type': 'application/json',
  2038. },
  2039. body: JSON.stringify({
  2040. playlist_name: 'Favorites',
  2041. files: updatedFavorites
  2042. })
  2043. });
  2044. if (!updateResponse.ok) {
  2045. throw new Error('Failed to update favorites playlist');
  2046. }
  2047. } catch (error) {
  2048. throw new Error(`Failed to remove from favorites: ${error.message}`);
  2049. }
  2050. }
  2051. // Update all heart icons based on current favorites
  2052. function updateAllHeartIcons() {
  2053. favoritePatterns.forEach(pattern => {
  2054. const heartIcon = document.getElementById('heart-' + pattern.replace(/[^a-zA-Z0-9]/g, '_'));
  2055. if (heartIcon) {
  2056. heartIcon.textContent = 'favorite';
  2057. heartIcon.className = 'material-icons text-lg text-red-500 hover:text-red-600 transition-colors';
  2058. // Make heart permanently visible when favorited
  2059. heartIcon.parentElement.className = heartIcon.parentElement.className.replace('opacity-0 group-hover:opacity-100', 'opacity-100');
  2060. }
  2061. });
  2062. }