1
0

index.js 95 KB

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