frontend.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. (function ($) {
  2. 'use strict';
  3. $(document).ready(function () {
  4. var $wrap = $('.studiou-fpp-upload-wrap');
  5. if (!$wrap.length) {
  6. return;
  7. }
  8. // ==========================================
  9. // Config + data
  10. // ==========================================
  11. var cfg = {
  12. productId: parseInt($wrap.data('product-id'), 10) || 0,
  13. maxFileSize: parseInt($wrap.data('max-file-size'), 10) || 50,
  14. maxUploads: parseInt($wrap.data('max-uploads'), 10) || 0,
  15. chunkSize: parseInt(studiouWcfppFront.chunkSize, 10) || 1048576
  16. };
  17. var i18n = studiouWcfppFront.i18n || {};
  18. var data = window.studiouFppCardData || {variants: [], batchFiles: []};
  19. var variants = data.variants || [];
  20. var $dropzone = $('#studiou-fpp-dropzone');
  21. var $fileInput = $('#studiou-fpp-file-input');
  22. var $cards = $('#studiou-fpp-cards');
  23. var $messages = $wrap.find('.studiou-fpp-messages');
  24. var originalGallery = {};
  25. // ==========================================
  26. // Bootstrap
  27. // ==========================================
  28. initExistingCards();
  29. initDropzone();
  30. initCardDelegation();
  31. initOverviewDelegation();
  32. initLightbox();
  33. initOverviewThumbClicks();
  34. applyHeroImage(data.heroPreviewUrl);
  35. // ==========================================
  36. // Card construction
  37. // ==========================================
  38. function initExistingCards() {
  39. (data.batchFiles || []).forEach(function (f) {
  40. var $card = buildCard({
  41. fileRecordId: f.file_record_id,
  42. attachmentId: f.attachment_id,
  43. fileName: f.file_name,
  44. thumbUrl: f.thumb_url,
  45. previewUrl: f.preview_url || f.thumb_url,
  46. variationId: f.variation_id || 0,
  47. uploading: false
  48. });
  49. $cards.append($card);
  50. });
  51. refreshMaxReachedState();
  52. }
  53. function buildCard(opts) {
  54. var $card = $('<div class="studiou-fpp-card"></div>');
  55. $card.attr('data-file-record-id', opts.fileRecordId || '');
  56. $card.attr('data-attachment-id', opts.attachmentId || '');
  57. if (opts.uploading) $card.addClass('studiou-fpp-card-uploading');
  58. // Remove-upload button (×)
  59. $card.append('<button type="button" class="studiou-fpp-card-remove" title="' +
  60. escAttr(i18n.removeFile || 'Remove') + '" aria-label="' +
  61. escAttr(i18n.removeFile || 'Remove') + '">&times;</button>');
  62. // Thumb column
  63. var $thumb = $('<div class="studiou-fpp-card-thumb"></div>');
  64. if (opts.thumbUrl) {
  65. var $img = $('<img>').attr('src', opts.thumbUrl).attr('alt', opts.fileName || '');
  66. if (opts.previewUrl) {
  67. $img.attr('data-preview-url', opts.previewUrl);
  68. }
  69. $thumb.append($img);
  70. } else {
  71. $thumb.append('<div class="studiou-fpp-card-thumb-placeholder"></div>');
  72. }
  73. // Element-level click binding — survives even if something intercepts bubble-phase
  74. // or capture-phase on document. Fires at target phase for clicks inside $thumb.
  75. bindThumbClick($thumb[0]);
  76. var $progress = $('<div class="studiou-fpp-card-progress"></div>');
  77. $progress.append('<div class="studiou-fpp-card-progress-fill"></div>');
  78. $progress.append('<span class="studiou-fpp-card-progress-text">0%</span>');
  79. if (!opts.uploading) {
  80. $progress.hide();
  81. }
  82. $thumb.append($progress);
  83. $card.append($thumb);
  84. // Body column
  85. var $body = $('<div class="studiou-fpp-card-body"></div>');
  86. $body.append($('<div class="studiou-fpp-card-name"></div>').text(opts.fileName || ''));
  87. var $controls = $('<div class="studiou-fpp-card-controls"></div>');
  88. $controls.append(buildVariantSelect(opts.variationId || 0));
  89. $controls.append(buildQtyStepper());
  90. $body.append($controls);
  91. var $priceRow = $('<div class="studiou-fpp-card-price-row"></div>');
  92. $priceRow.append('<span class="studiou-fpp-card-price">&mdash;</span>');
  93. $priceRow.append('<span class="studiou-fpp-card-badge" style="display:none;"></span>');
  94. var $enlargeBtn = $('<button type="button" class="studiou-fpp-card-enlarge"></button>').text(i18n.enlarge || 'Enlarge');
  95. // Direct target-phase binding — primitive, runs regardless of delegation state.
  96. $enlargeBtn[0].onclick = onEnlargeClick;
  97. $priceRow.append($enlargeBtn);
  98. $priceRow.append('<button type="button" class="button studiou-fpp-card-addtocart">' +
  99. escHtml(i18n.addToCart || 'Add to cart') + '</button>');
  100. $body.append($priceRow);
  101. $card.append($body);
  102. if (!opts.uploading) {
  103. updateCardPrice($card);
  104. }
  105. return $card;
  106. }
  107. function buildVariantSelect(initialVariationId) {
  108. var $select = $('<select class="studiou-fpp-card-variant"></select>');
  109. $select.append($('<option></option>').val(0).text(i18n.selectVariant || 'Select variant'));
  110. for (var i = 0; i < variants.length; i++) {
  111. var v = variants[i];
  112. // <option> text nodes cannot render HTML, so use a plain-text price formatter
  113. var priceLabel = v.base_price ? ' — ' + formatPricePlain(v.base_price) : '';
  114. var label = v.label + priceLabel;
  115. if (!v.in_stock) {
  116. label += ' — ' + (i18n.outOfStock || 'out of stock');
  117. }
  118. var $opt = $('<option></option>')
  119. .val(v.id)
  120. .text(label)
  121. .attr('data-base-price', v.base_price);
  122. if (!v.in_stock) {
  123. $opt.prop('disabled', true);
  124. }
  125. $select.append($opt);
  126. }
  127. if (initialVariationId) {
  128. $select.val(initialVariationId);
  129. }
  130. return $select;
  131. }
  132. function buildQtyStepper() {
  133. var $stepper = $('<div class="studiou-fpp-card-qty"></div>');
  134. $stepper.append('<button type="button" class="studiou-fpp-qty-btn studiou-fpp-qty-minus">&minus;</button>');
  135. $stepper.append('<input type="number" class="studiou-fpp-qty-input" min="1" step="1" value="1">');
  136. $stepper.append('<button type="button" class="studiou-fpp-qty-btn studiou-fpp-qty-plus">+</button>');
  137. return $stepper;
  138. }
  139. // ==========================================
  140. // Card live updates
  141. // ==========================================
  142. function initCardDelegation() {
  143. $cards.on('change', '.studiou-fpp-card-variant', function () {
  144. updateCardPrice($(this).closest('.studiou-fpp-card'));
  145. });
  146. $cards.on('input change keyup', '.studiou-fpp-qty-input', function () {
  147. updateCardPrice($(this).closest('.studiou-fpp-card'));
  148. });
  149. $cards.on('click', '.studiou-fpp-qty-plus', function () {
  150. var $input = $(this).closest('.studiou-fpp-card-qty').find('.studiou-fpp-qty-input');
  151. $input.val((parseInt($input.val(), 10) || 1) + 1).trigger('change');
  152. });
  153. $cards.on('click', '.studiou-fpp-qty-minus', function () {
  154. var $input = $(this).closest('.studiou-fpp-card-qty').find('.studiou-fpp-qty-input');
  155. var v = Math.max(1, (parseInt($input.val(), 10) || 1) - 1);
  156. $input.val(v).trigger('change');
  157. });
  158. $cards.on('click', '.studiou-fpp-card-addtocart', function () {
  159. onAddToCartClick($(this).closest('.studiou-fpp-card'));
  160. });
  161. $cards.on('click', '.studiou-fpp-card-remove', function () {
  162. onRemoveUploadClick($(this).closest('.studiou-fpp-card'));
  163. });
  164. }
  165. function findVariant(variationId) {
  166. variationId = parseInt(variationId, 10) || 0;
  167. if (!variationId) return null;
  168. for (var i = 0; i < variants.length; i++) {
  169. if (variants[i].id === variationId) return variants[i];
  170. }
  171. return null;
  172. }
  173. function resolveTier(tiers, qty) {
  174. if (!tiers || !tiers.length) return null;
  175. var match = null;
  176. for (var i = 0; i < tiers.length; i++) {
  177. if (tiers[i].from_qty <= qty) match = tiers[i];
  178. else break;
  179. }
  180. return match;
  181. }
  182. function updateCardPrice($card) {
  183. var $price = $card.find('.studiou-fpp-card-price');
  184. var $badge = $card.find('.studiou-fpp-card-badge');
  185. var $btn = $card.find('.studiou-fpp-card-addtocart');
  186. var variationId = parseInt($card.find('.studiou-fpp-card-variant').val(), 10) || 0;
  187. var qty = Math.max(1, parseInt($card.find('.studiou-fpp-qty-input').val(), 10) || 1);
  188. var variant = findVariant(variationId);
  189. if (!variant || !variant.base_price) {
  190. $price.html('&mdash;');
  191. $badge.hide();
  192. $btn.prop('disabled', true);
  193. return;
  194. }
  195. var tier = resolveTier(variant.tiers || [], qty);
  196. var unit = variant.base_price;
  197. if (tier && tier.percent > 0) {
  198. unit = variant.base_price * (1 - (tier.percent / 100));
  199. $badge.show().text('−' + formatPercent(tier.percent));
  200. } else {
  201. $badge.hide();
  202. }
  203. var lineTotal = unit * qty;
  204. $price.html(formatPriceHtml(lineTotal));
  205. var uploading = $card.hasClass('studiou-fpp-card-uploading');
  206. $btn.prop('disabled', uploading);
  207. }
  208. // ==========================================
  209. // Upload dropzone
  210. // ==========================================
  211. function initDropzone() {
  212. $dropzone.on('dragover dragenter', function (e) {
  213. e.preventDefault(); e.stopPropagation();
  214. $(this).addClass('studiou-fpp-dragover');
  215. });
  216. $dropzone.on('dragleave drop', function (e) {
  217. e.preventDefault(); e.stopPropagation();
  218. $(this).removeClass('studiou-fpp-dragover');
  219. });
  220. $dropzone.on('drop', function (e) {
  221. var files = e.originalEvent.dataTransfer.files;
  222. enqueueFiles(files);
  223. });
  224. $dropzone.on('click', function () {
  225. if ($dropzone.hasClass('studiou-fpp-dropzone-disabled')) return;
  226. $fileInput.trigger('click');
  227. });
  228. $fileInput.on('change', function () {
  229. enqueueFiles(this.files);
  230. $fileInput.val('');
  231. });
  232. }
  233. var uploadQueue = [];
  234. var activeUpload = false;
  235. function enqueueFiles(fileList) {
  236. if (!fileList || !fileList.length) return;
  237. clearMessages();
  238. if (cfg.maxUploads > 0) {
  239. var existing = $cards.children('.studiou-fpp-card').length;
  240. var available = Math.max(0, cfg.maxUploads - existing - uploadQueue.length);
  241. if (available <= 0) {
  242. showMessage(formatI18n(i18n.maxUploadsReached, cfg.maxUploads), 'error');
  243. return;
  244. }
  245. if (fileList.length > available) {
  246. showMessage(formatI18n(i18n.maxUploadsReached, cfg.maxUploads), 'error');
  247. }
  248. for (var i = 0; i < Math.min(fileList.length, available); i++) {
  249. pushFile(fileList[i]);
  250. }
  251. } else {
  252. for (var j = 0; j < fileList.length; j++) {
  253. pushFile(fileList[j]);
  254. }
  255. }
  256. refreshMaxReachedState();
  257. drainQueue();
  258. }
  259. function pushFile(file) {
  260. var maxBytes = cfg.maxFileSize * 1024 * 1024;
  261. if (file.size > maxBytes) {
  262. showMessage(formatI18n(i18n.fileTooLarge, cfg.maxFileSize), 'error');
  263. return;
  264. }
  265. var $card = buildCard({
  266. fileRecordId: 0,
  267. attachmentId: 0,
  268. fileName: file.name,
  269. thumbUrl: '',
  270. variationId: 0,
  271. uploading: true
  272. });
  273. $cards.append($card);
  274. uploadQueue.push({file: file, $card: $card});
  275. }
  276. function drainQueue() {
  277. if (activeUpload || !uploadQueue.length) return;
  278. activeUpload = true;
  279. var next = uploadQueue.shift();
  280. uploadOne(next.file, next.$card, function () {
  281. activeUpload = false;
  282. drainQueue();
  283. });
  284. }
  285. function uploadOne(file, $card, done) {
  286. var totalChunks = Math.ceil(file.size / cfg.chunkSize);
  287. var uploadId = 'upload_' + Date.now() + '_' + Math.random().toString(36).slice(2, 10);
  288. var currentChunk = 0;
  289. var $fill = $card.find('.studiou-fpp-card-progress-fill');
  290. var $text = $card.find('.studiou-fpp-card-progress-text');
  291. $card.find('.studiou-fpp-card-progress').show();
  292. function next() {
  293. var start = currentChunk * cfg.chunkSize;
  294. var end = Math.min(start + cfg.chunkSize, file.size);
  295. var blob = file.slice(start, end);
  296. var form = new FormData();
  297. form.append('action', 'studiou_wcfpp_upload_chunk');
  298. form.append('nonce', studiouWcfppFront.nonce);
  299. form.append('product_id', cfg.productId);
  300. form.append('upload_id', uploadId);
  301. form.append('chunk_index', currentChunk);
  302. form.append('total_chunks', totalChunks);
  303. form.append('file_name', file.name);
  304. form.append('file_size', file.size);
  305. form.append('chunk', blob, 'chunk');
  306. var isLast = (currentChunk === totalChunks - 1);
  307. if (isLast) {
  308. $fill.css('width', '100%');
  309. $text.text(i18n.processing || 'Processing...');
  310. }
  311. $.ajax({
  312. url: studiouWcfppFront.ajaxUrl,
  313. type: 'POST',
  314. data: form,
  315. processData: false,
  316. contentType: false,
  317. timeout: isLast ? 120000 : 30000,
  318. success: function (response) {
  319. if (!response.success) {
  320. failUpload($card, response.data ? response.data.message : (i18n.uploadError || 'Upload failed.'));
  321. done();
  322. return;
  323. }
  324. if (!response.data.complete) {
  325. currentChunk++;
  326. var pct = Math.round((currentChunk / totalChunks) * 100);
  327. $fill.css('width', pct + '%');
  328. $text.text(pct + '%');
  329. next();
  330. } else {
  331. finishUpload($card, response.data);
  332. done();
  333. }
  334. },
  335. error: function () {
  336. failUpload($card, i18n.uploadError || 'Upload failed.');
  337. done();
  338. }
  339. });
  340. }
  341. next();
  342. }
  343. function finishUpload($card, res) {
  344. $card.removeClass('studiou-fpp-card-uploading');
  345. $card.find('.studiou-fpp-card-progress').hide();
  346. $card.attr('data-file-record-id', res.file_record_id);
  347. $card.attr('data-attachment-id', res.attachment_id);
  348. var previewUrl = res.preview_url || res.thumbnail_url;
  349. var $img = $card.find('.studiou-fpp-card-thumb img');
  350. if ($img.length) {
  351. $img.attr('src', res.thumbnail_url).attr('data-preview-url', previewUrl);
  352. } else {
  353. $card.find('.studiou-fpp-card-thumb-placeholder').replaceWith(
  354. $('<img>').attr('src', res.thumbnail_url)
  355. .attr('alt', res.file_name)
  356. .attr('data-preview-url', previewUrl)
  357. );
  358. }
  359. updateCardPrice($card);
  360. refreshMaxReachedState();
  361. // If this is now the first/only card, swap the hero gallery image
  362. if ($cards.children('.studiou-fpp-card').index($card) === 0) {
  363. applyHeroImage(previewUrl);
  364. }
  365. }
  366. function failUpload($card, message) {
  367. $card.remove();
  368. showMessage(message, 'error');
  369. refreshMaxReachedState();
  370. }
  371. function refreshMaxReachedState() {
  372. if (cfg.maxUploads <= 0) return;
  373. var reached = $cards.children('.studiou-fpp-card').length >= cfg.maxUploads;
  374. $dropzone.toggleClass('studiou-fpp-dropzone-disabled', reached);
  375. }
  376. // ==========================================
  377. // Remove upload (per-card × button)
  378. // ==========================================
  379. function onRemoveUploadClick($card) {
  380. var fileRecordId = parseInt($card.attr('data-file-record-id'), 10) || 0;
  381. if (!fileRecordId) {
  382. // Still uploading — just cancel locally
  383. $card.remove();
  384. refreshMaxReachedState();
  385. return;
  386. }
  387. $.ajax({
  388. url: studiouWcfppFront.ajaxUrl,
  389. type: 'POST',
  390. data: {
  391. action: 'studiou_wcfpp_remove_upload',
  392. nonce: studiouWcfppFront.nonce,
  393. file_record_id: fileRecordId
  394. },
  395. success: function (response) {
  396. if (response.success) {
  397. var wasFirst = ($cards.children('.studiou-fpp-card').index($card) === 0);
  398. $card.remove();
  399. refreshMaxReachedState();
  400. if (wasFirst) {
  401. var $nextFirst = $cards.children('.studiou-fpp-card').first();
  402. if ($nextFirst.length) {
  403. var nextImg = $nextFirst.find('.studiou-fpp-card-thumb img').attr('src');
  404. applyHeroImage(nextImg || '');
  405. } else {
  406. restoreHeroImage();
  407. }
  408. }
  409. } else {
  410. showMessage(response.data ? response.data.message : (i18n.error || 'Error'), 'error');
  411. }
  412. },
  413. error: function () {
  414. showMessage(i18n.error || 'Error', 'error');
  415. }
  416. });
  417. }
  418. // ==========================================
  419. // Add to cart
  420. // ==========================================
  421. function onAddToCartClick($card) {
  422. var fileRecordId = parseInt($card.attr('data-file-record-id'), 10) || 0;
  423. var variationId = parseInt($card.find('.studiou-fpp-card-variant').val(), 10) || 0;
  424. var qty = Math.max(1, parseInt($card.find('.studiou-fpp-qty-input').val(), 10) || 1);
  425. if (!fileRecordId) {
  426. showMessage(i18n.uploadFile || 'Please upload a file.', 'error');
  427. return;
  428. }
  429. if (!variationId) {
  430. showMessage(i18n.selectVariant || 'Please select a variant.', 'error');
  431. return;
  432. }
  433. var $btn = $card.find('.studiou-fpp-card-addtocart');
  434. $btn.prop('disabled', true);
  435. $.ajax({
  436. url: studiouWcfppFront.ajaxUrl,
  437. type: 'POST',
  438. data: {
  439. action: 'studiou_wcfpp_add_file_to_cart',
  440. nonce: studiouWcfppFront.nonce,
  441. file_record_id: fileRecordId,
  442. variation_id: variationId,
  443. quantity: qty
  444. },
  445. success: function (response) {
  446. if (response.success) {
  447. showMessage(i18n.addedToCart || 'Added to cart.', 'success');
  448. if (response.data && response.data.overview_html) {
  449. updateOverview(response.data.overview_html);
  450. }
  451. } else {
  452. showMessage(response.data ? response.data.message : (i18n.addToCartError || 'Could not add to cart.'), 'error');
  453. }
  454. },
  455. error: function () {
  456. showMessage(i18n.addToCartError || 'Could not add to cart.', 'error');
  457. },
  458. complete: function () {
  459. $btn.prop('disabled', false);
  460. }
  461. });
  462. }
  463. // ==========================================
  464. // Order overview
  465. // ==========================================
  466. function initOverviewDelegation() {
  467. // Remove-line on overview panel (cart-only, upload stays)
  468. $(document).on('click', '.studiou-fpp-overview-remove', function (e) {
  469. var $link = $(this);
  470. var href = $link.attr('href');
  471. // Only intercept if the link has a nonce arg — otherwise let browser navigate
  472. if (!href || href.indexOf('studiou-fpp-remove-line') < 0) return;
  473. e.preventDefault();
  474. var $line = $link.closest('.studiou-fpp-overview-line');
  475. var key = $line.data('cart-item-key');
  476. if (!key) return;
  477. $.ajax({
  478. url: studiouWcfppFront.ajaxUrl,
  479. type: 'POST',
  480. data: {
  481. action: 'studiou_wcfpp_remove_cart_line',
  482. nonce: studiouWcfppFront.nonce,
  483. cart_item_key: key
  484. },
  485. success: function (response) {
  486. if (response.success && response.data && response.data.overview_html) {
  487. updateOverview(response.data.overview_html);
  488. } else if (!response.success) {
  489. showMessage(response.data ? response.data.message : (i18n.error || 'Error'), 'error');
  490. }
  491. },
  492. error: function () {
  493. showMessage(i18n.error || 'Error', 'error');
  494. }
  495. });
  496. });
  497. }
  498. function updateOverview(html) {
  499. var $new = $(html);
  500. var $existing = $('#studiou-fpp-overview');
  501. if ($existing.length) {
  502. $existing.replaceWith($new);
  503. } else {
  504. $wrap.after($new);
  505. }
  506. initOverviewThumbClicks();
  507. $(document).trigger('studiou-fpp:cart-updated');
  508. }
  509. // ==========================================
  510. // Hero image
  511. // ==========================================
  512. function applyHeroImage(url) {
  513. if (!url) return;
  514. var selectors = [
  515. '.woocommerce-product-gallery__image img',
  516. '.product .wp-post-image',
  517. '.product-image img',
  518. '.product-thumbnail img',
  519. '.entry-summary img.attachment-woocommerce_thumbnail',
  520. '.product-gallery img:first'
  521. ];
  522. var $img = null;
  523. for (var i = 0; i < selectors.length; i++) {
  524. $img = $(selectors[i]).first();
  525. if ($img.length) break;
  526. }
  527. if (!$img || !$img.length) return;
  528. if (!originalGallery.src) {
  529. originalGallery.src = $img.attr('src');
  530. originalGallery.srcset = $img.attr('srcset') || '';
  531. originalGallery.sizes = $img.attr('sizes') || '';
  532. var $link = $img.closest('a');
  533. if ($link.length) originalGallery.href = $link.attr('href');
  534. }
  535. $img.attr('src', url).removeAttr('srcset').removeAttr('sizes');
  536. var $a = $img.closest('a');
  537. if ($a.length) $a.attr('href', url);
  538. }
  539. // ==========================================
  540. // Lightbox (click thumbnail → enlarged preview)
  541. // ==========================================
  542. var $lightbox = null;
  543. // Attach a target-phase click listener directly on a thumbnail element.
  544. // Element-level listeners are the most reliable form of click binding — no
  545. // delegation, no capture/bubble surprises. Called from buildCard + finishUpload
  546. // (upload cards) and from initOverviewThumbClicks (after every overview render).
  547. function bindThumbClick(el) {
  548. if (!el || el.__studiouFppBound) return;
  549. el.__studiouFppBound = true;
  550. el.addEventListener('click', function (ev) {
  551. var t = ev.target;
  552. if (t && t.closest && t.closest('button, input, select, textarea, a')) return;
  553. var card = el.closest ? el.closest('.studiou-fpp-card') : null;
  554. if (card && card.classList.contains('studiou-fpp-card-uploading')) return;
  555. var img = el.matches && el.matches('.studiou-fpp-overview-thumb')
  556. ? el
  557. : (el.querySelector ? el.querySelector('img') : null);
  558. if (!img) return;
  559. var url = img.getAttribute('data-preview-url') || img.getAttribute('src');
  560. if (!url) return;
  561. var name = '';
  562. if (card) {
  563. var nameEl = card.querySelector('.studiou-fpp-card-name');
  564. name = nameEl ? nameEl.textContent : '';
  565. } else {
  566. name = img.getAttribute('data-file-name') || img.getAttribute('alt') || '';
  567. }
  568. ev.preventDefault();
  569. ev.stopPropagation();
  570. openLightbox(url, name);
  571. });
  572. }
  573. // Explicit "Enlarge" button handler — survives any parent-level click interceptor
  574. // because clicks on <button type="button"> don't match the thumb-image selectors that
  575. // theme lightboxes (iLightBox/Magnific) delegate to.
  576. function onEnlargeClick(ev) {
  577. ev.preventDefault();
  578. ev.stopPropagation();
  579. var btn = this;
  580. var card = btn.closest('.studiou-fpp-card');
  581. var line = btn.closest('.studiou-fpp-overview-line');
  582. var img, name;
  583. if (card) {
  584. img = card.querySelector('.studiou-fpp-card-thumb img');
  585. var nameEl = card.querySelector('.studiou-fpp-card-name');
  586. name = nameEl ? nameEl.textContent : '';
  587. } else if (line) {
  588. img = line.querySelector('.studiou-fpp-overview-thumb');
  589. name = img ? (img.getAttribute('data-file-name') || img.getAttribute('alt') || '') : '';
  590. }
  591. if (!img) return;
  592. var url = img.getAttribute('data-preview-url') || img.getAttribute('src');
  593. if (!url) return;
  594. openLightbox(url, name);
  595. }
  596. // (Re)bind all overview thumbs — called after initial render and after updateOverview.
  597. function initOverviewThumbClicks() {
  598. var nodes = document.querySelectorAll('.studiou-fpp-overview-thumb');
  599. for (var i = 0; i < nodes.length; i++) {
  600. bindThumbClick(nodes[i]);
  601. }
  602. var btns = document.querySelectorAll('.studiou-fpp-overview-enlarge');
  603. for (var j = 0; j < btns.length; j++) {
  604. btns[j].onclick = onEnlargeClick;
  605. }
  606. }
  607. function initLightbox() {
  608. $lightbox = $(
  609. '<div class="studiou-fpp-lightbox" role="dialog" aria-modal="true" style="display:none;">' +
  610. '<button type="button" class="studiou-fpp-lightbox-close" aria-label="' + escAttr(i18n.close || 'Close') + '">&times;</button>' +
  611. '<div class="studiou-fpp-lightbox-inner">' +
  612. '<img class="studiou-fpp-lightbox-img" alt="" />' +
  613. '<div class="studiou-fpp-lightbox-caption"></div>' +
  614. '</div>' +
  615. '</div>'
  616. );
  617. $('body').append($lightbox);
  618. // Enlarge button — primary, reliable opener. Delegated on document so newly
  619. // rendered cards and overview lines pick it up automatically.
  620. $(document).on('click', '.studiou-fpp-card-enlarge, .studiou-fpp-overview-enlarge', function (e) {
  621. onEnlargeClick.call(this, e);
  622. });
  623. // Use native capture-phase listener so theme/plugin handlers that stopPropagation
  624. // on <img> clicks (common in gallery-lightbox plugins) can't swallow us. Target the
  625. // .studiou-fpp-card-thumb wrapper, not just the <img>, so any click inside the
  626. // thumbnail — including padding around the image — opens the preview.
  627. document.addEventListener('click', function (ev) {
  628. var target = ev.target;
  629. if (!target || !target.closest) return;
  630. // Ignore clicks on interactive controls (remove button, progress text, etc.)
  631. if (target.closest('button, input, select, textarea, a')) return;
  632. var cardThumb = target.closest('.studiou-fpp-card-thumb');
  633. if (cardThumb) {
  634. var card = cardThumb.closest('.studiou-fpp-card');
  635. if (!card || card.classList.contains('studiou-fpp-card-uploading')) return;
  636. var img = cardThumb.querySelector('img');
  637. if (!img) return;
  638. ev.preventDefault();
  639. ev.stopPropagation();
  640. var nameEl = card.querySelector('.studiou-fpp-card-name');
  641. openLightbox(
  642. img.getAttribute('data-preview-url') || img.getAttribute('src'),
  643. nameEl ? nameEl.textContent : ''
  644. );
  645. return;
  646. }
  647. var overviewImg = target.closest('.studiou-fpp-overview-thumb');
  648. if (overviewImg) {
  649. ev.preventDefault();
  650. ev.stopPropagation();
  651. openLightbox(
  652. overviewImg.getAttribute('data-preview-url') || overviewImg.getAttribute('src'),
  653. overviewImg.getAttribute('data-file-name') || overviewImg.getAttribute('alt') || ''
  654. );
  655. }
  656. }, true);
  657. // Close: × button, backdrop click, ESC key
  658. $lightbox.on('click', '.studiou-fpp-lightbox-close', closeLightbox);
  659. $lightbox.on('click', function (e) {
  660. if (e.target === this) closeLightbox();
  661. });
  662. $(document).on('keydown.studiouFppLightbox', function (e) {
  663. if (e.key === 'Escape' && $lightbox && $lightbox.is(':visible')) {
  664. closeLightbox();
  665. }
  666. });
  667. }
  668. function openLightbox(url, caption) {
  669. if (!url) return;
  670. // Fallback: if the overlay DOM somehow failed to initialize, at least open the
  671. // preview in a new tab so the button is never a no-op.
  672. if (!$lightbox || !$lightbox.length) {
  673. window.open(url, '_blank', 'noopener');
  674. return;
  675. }
  676. $lightbox.find('.studiou-fpp-lightbox-img').attr('src', url).attr('alt', caption || '');
  677. $lightbox.find('.studiou-fpp-lightbox-caption').text(caption || '');
  678. $lightbox.css('display', 'flex');
  679. $('body').addClass('studiou-fpp-lightbox-open');
  680. }
  681. function closeLightbox() {
  682. if (!$lightbox) return;
  683. $lightbox.hide();
  684. $lightbox.find('.studiou-fpp-lightbox-img').attr('src', '');
  685. $('body').removeClass('studiou-fpp-lightbox-open');
  686. }
  687. function restoreHeroImage() {
  688. if (!originalGallery.src) return;
  689. var selectors = [
  690. '.woocommerce-product-gallery__image img',
  691. '.product .wp-post-image',
  692. '.product-image img',
  693. '.product-thumbnail img',
  694. '.entry-summary img.attachment-woocommerce_thumbnail',
  695. '.product-gallery img:first'
  696. ];
  697. var $img = null;
  698. for (var i = 0; i < selectors.length; i++) {
  699. $img = $(selectors[i]).first();
  700. if ($img.length) break;
  701. }
  702. if (!$img || !$img.length) return;
  703. $img.attr('src', originalGallery.src);
  704. if (originalGallery.srcset) $img.attr('srcset', originalGallery.srcset);
  705. if (originalGallery.sizes) $img.attr('sizes', originalGallery.sizes);
  706. if (originalGallery.href) $img.closest('a').attr('href', originalGallery.href);
  707. originalGallery = {};
  708. }
  709. // ==========================================
  710. // Helpers
  711. // ==========================================
  712. function showMessage(text, type) {
  713. var cls = type === 'error' ? 'studiou-fpp-msg-error'
  714. : type === 'success' ? 'studiou-fpp-msg-success'
  715. : 'studiou-fpp-msg-info';
  716. $messages.html('<div class="studiou-fpp-msg ' + cls + '">' + escHtml(text) + '</div>');
  717. }
  718. function clearMessages() { $messages.empty(); }
  719. function escHtml(str) {
  720. var div = document.createElement('div');
  721. div.appendChild(document.createTextNode(str == null ? '' : String(str)));
  722. return div.innerHTML;
  723. }
  724. function escAttr(str) {
  725. return String(str == null ? '' : str).replace(/"/g, '&quot;');
  726. }
  727. function formatI18n(tpl, val) {
  728. if (!tpl) return String(val);
  729. return tpl.replace('%d', val).replace('%s', val);
  730. }
  731. function formatPercent(p) {
  732. var n = parseFloat(p) || 0;
  733. var str = n.toFixed(2).replace(/\.?0+$/, '');
  734. return str + ' %';
  735. }
  736. function formatPrice(amount) {
  737. return formatPriceHtml(amount);
  738. }
  739. // Plain-text price (no HTML) — used for <option> labels where spans aren't rendered
  740. function formatPricePlain(amount) {
  741. var c = studiouWcfppFront.currency || {};
  742. var decimals = parseInt(c.decimals, 10); if (isNaN(decimals)) decimals = 2;
  743. var decSep = c.decimalSeparator || '.';
  744. var thouSep = c.thousandSeparator || ',';
  745. var fmt = c.priceFormat || '%1$s%2$s';
  746. var symbol = c.symbol || '';
  747. var fixed = parseFloat(amount).toFixed(decimals);
  748. var parts = fixed.split('.');
  749. var intPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thouSep);
  750. var decPart = parts.length > 1 ? parts[1] : '';
  751. var numStr = decPart ? intPart + decSep + decPart : intPart;
  752. // strip any HTML tags that might arrive from priceFormat (defensive)
  753. return fmt.replace('%1$s', symbol).replace('%2$s', numStr).replace(/<[^>]*>/g, '');
  754. }
  755. function formatPriceHtml(amount) {
  756. var c = studiouWcfppFront.currency || {};
  757. var decimals = parseInt(c.decimals, 10); if (isNaN(decimals)) decimals = 2;
  758. var decSep = c.decimalSeparator || '.';
  759. var thouSep = c.thousandSeparator || ',';
  760. var fmt = c.priceFormat || '%1$s%2$s';
  761. var symbol = c.symbol || '';
  762. var fixed = parseFloat(amount).toFixed(decimals);
  763. var parts = fixed.split('.');
  764. var intPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thouSep);
  765. var decPart = parts.length > 1 ? parts[1] : '';
  766. var numStr = decPart ? intPart + decSep + decPart : intPart;
  767. var sym = '<span class="woocommerce-Price-currencySymbol">' + symbol + '</span>';
  768. return '<span class="woocommerce-Price-amount amount">' +
  769. fmt.replace('%1$s', sym).replace('%2$s', numStr) +
  770. '</span>';
  771. }
  772. });
  773. })(jQuery);