From dbabe431696f2e2a681960dc4c2a9943cccb7281 Mon Sep 17 00:00:00 2001 From: asdfzdfj Date: Sat, 18 May 2024 14:33:37 +0700 Subject: [PATCH] preview controller memoize response + clear on close adjusted preview controller to clear its content on close, but at the same time also memoize the embed response from the server the should help in dealing with e.g. youtube embed preview where simply hiding the preview container would not make it stop, and there's no good way to universally stop embed media players other than to erase them out entirely, while not making extra requests to the server when the preview is being repeatedly shown/hidden in the same page session --- assets/controllers/preview_controller.js | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/assets/controllers/preview_controller.js b/assets/controllers/preview_controller.js index 0da34e6cb..286323c4b 100644 --- a/assets/controllers/preview_controller.js +++ b/assets/controllers/preview_controller.js @@ -12,6 +12,9 @@ export default class extends Controller { static targets = ['container']; static throttles = ['show']; + /** memoization of fetched embed response */ + fetchedResponse = {}; + connect() { useThrottle(this, { wait: 1000 }); @@ -43,6 +46,21 @@ export default class extends Controller { await this.show(event); } + async fetchEmbed(url) { + if (this.fetchedResponse[url]) { + return this.fetchedResponse[url]; + } + + let response = await fetch(router().generate('ajax_fetch_embed', { url }), { method: 'GET' }); + + response = await ok(response); + response = await response.json(); + + this.fetchedResponse[url] = response; + + return response; + } + async show(event) { event.preventDefault(); @@ -55,10 +73,7 @@ export default class extends Controller { try { this.loadingValue = true; - let response = await fetch(router().generate('ajax_fetch_embed', { url: event.params.url }), { method: 'GET' }); - - response = await ok(response); - response = await response.json(); + const response = await this.fetchEmbed(event.params.url); this.containerTarget.innerHTML = response.html; this.containerTarget.classList.remove('hidden');