index.js 94 KB

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