FIX: Use array to keep best link for each onebox (#13717)

FIX: Use array to keep best link for each onebox (#13717)

Use a Map to hold the best link element for each Onebox HTML element.

Using an Object did not work as intended because Object can use only Strings or Symbols as keys. Using HTML elements (representing oneboxes) as keys most probably converted them to some generic string and sometimes different Oneboxes were associated same key. It seems to be browser and content dependent, without any clear indication of what is happening internally.

This bug caused link counts to show only for the last Onebox because the best link from the last Onebox was considered for all the other Oneboxes.

diff --git a/app/assets/javascripts/discourse/app/widgets/post-cooked.js b/app/assets/javascripts/discourse/app/widgets/post-cooked.js
index 35c65f9..f115de1 100644
--- a/app/assets/javascripts/discourse/app/widgets/post-cooked.js
+++ b/app/assets/javascripts/discourse/app/widgets/post-cooked.js
@@ -98,13 +98,13 @@ export default class PostCooked {
     // find the best <a> element in each onebox and display link counts only
     // for that one (the best element is the most significant one to the
     // viewer)
-    const bestElements = [];
+    const bestElements = new Map();
     $html[0].querySelectorAll("aside.onebox").forEach((onebox) => {
       // look in headings first
       for (let i = 1; i <= 6; ++i) {
         const hLinks = onebox.querySelectorAll(`h${i} a[href]`);
         if (hLinks.length > 0) {
-          bestElements[onebox] = hLinks[0];
+          bestElements.set(onebox, hLinks[0]);
           return;
         }
       }
@@ -112,7 +112,7 @@ export default class PostCooked {
       // use the header otherwise
       const hLinks = onebox.querySelectorAll("header a[href]");
       if (hLinks.length > 0) {
-        bestElements[onebox] = hLinks[0];
+        bestElements.set(onebox, hLinks[0]);
       }
     });
 
@@ -142,8 +142,8 @@ export default class PostCooked {
           const $onebox = $link.closest(".onebox");
           if (
             $onebox.length === 0 ||
-            !bestElements[$onebox[0]] ||
-            bestElements[$onebox[0]] === $link[0]
+            !bestElements.has($onebox[0]) ||
+            bestElements.get($onebox[0]) === $link[0]
           ) {
             const title = I18n.t("topic_map.clicks", { count: lc.clicks });
             $link.append(

GitHub sha: 2318bd66a7debfa4e7fc7fa6ddd9a71d69a087c9

This commit appears in #13717 which was approved by ZogStriP. It was merged by nbianca.