1
0

index.js 73 KB

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