1
0

index.js 92 KB

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