index.js 92 KB

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