You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "rusackas (via GitHub)" <gi...@apache.org> on 2025/12/18 17:17:06 UTC

[PR] feat(docs): enhance Matomo analytics tracking [superset]

rusackas opened a new pull request, #36743:
URL: https://github.com/apache/superset/pull/36743

   ## Summary
   
   Enhances the Matomo analytics implementation on the Superset docs site to capture more comprehensive user behavior data. This addresses the observation that our stats are lower than other ASF projects.
   
   **New tracking features:**
   
   - **Site search tracking**: Tracks Algolia search queries (debounced, 3+ characters) with result counts using Matomo's `trackSiteSearch` API
   - **Download tracking**: Extends tracked file extensions to include PDF, ZIP, TAR, executables, office documents, and data files (CSV, JSON, YAML)
   - **Event tracking**:
     - External link clicks categorized by domain (GitHub, Slack, Stack Overflow, Mailing List, Preset, Kapa AI)
     - CTA button clicks (Get Started, etc.)
     - Video plays on homepage
   - **Outbound link categorization**: Better analytics segmentation for understanding which external resources users visit most
   
   **What this helps with:**
   - Understanding what users search for (and whether they find results)
   - Tracking engagement with key CTAs
   - Measuring video engagement
   - Understanding which external resources drive the most interest
   
   ## Test plan
   
   - [ ] Run docs site locally (`yarn start`) and verify console logs show tracking events
   - [ ] Test Algolia search triggers `trackSiteSearch` calls
   - [ ] Test clicking external links triggers categorized `trackEvent` calls
   - [ ] Test video play triggers `trackEvent` calls
   - [ ] Test CTA button clicks trigger `trackEvent` calls
   - [ ] Verify no errors in browser console
   
   ๐Ÿค– Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(docs): enhance Matomo analytics tracking [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #36743:
URL: https://github.com/apache/superset/pull/36743#issuecomment-3671303709

   ## Nitpicks ๐Ÿ”
   
   <table>
   <tr><td>๐Ÿ”’&nbsp;<strong>No security issues identified</strong></td></tr>
   <tr><td>โšก&nbsp;<strong>Recommended areas for review</strong><br><br>
   
   - [ ] <a href='https://github.com/apache/superset/pull/36743/files#diff-6c11de58a23373e465a47687ff83ed31ad19cd69bf858b8c65da26589e6258a0R193-R210'><strong>Event listener removal bug</strong></a><br>The code adds Docusaurus route listeners with an anonymous callback but attempts to remove them using `handleRouteChange`. Because the added listeners are anonymous functions, removeEventListener will not remove them โ€” causing memory leaks and duplicated handlers on navigation. Verify that listeners are registered with named references so they can be removed during cleanup.<br>
   
   - [ ] <a href='https://github.com/apache/superset/pull/36743/files#diff-6c11de58a23373e465a47687ff83ed31ad19cd69bf858b8c65da26589e6258a0R46-R67'><strong>matomoUrl / siteId guard</strong></a><br>The tracker is configured and the matomo script is appended using values from `customFields` (`matomoUrl`, `matomoSiteId`) without validating they exist or are valid strings. If they are undefined or empty the tracker URL will be malformed and matomo.js could fail to load. Consider early-return or validation before using them.<br>
   
   - [ ] <a href='https://github.com/apache/superset/pull/36743/files#diff-6c11de58a23373e465a47687ff83ed31ad19cd69bf858b8c65da26589e6258a0R86-R112'><strong>Non-http protocols tracked as external</strong></a><br>`handleLinkClick` uses `new URL(href, window.location.origin)` and treats any link with a different hostname as external. This will categorize `mailto:`, `tel:`, `javascript:`, `data:` and other non-HTTP(S) schemes as "External Link". Consider restricting tracking to `http:`/`https:` (or handling non-HTTP schemes differently).<br>
   
   - [ ] <a href='https://github.com/apache/superset/pull/36743/files#diff-6c11de58a23373e465a47687ff83ed31ad19cd69bf858b8c65da26589e6258a0R115-R145'><strong>Algolia observer may add duplicate listeners</strong></a><br>The MutationObserver attaches an `input` listener on discovered search inputs but does not guard against adding duplicate listeners if the same input is re-added or detected multiple times. This can produce multiple tracking events per user action. Consider marking inputs as instrumented or check for an existing handler.<br>
   
   </td></tr>
   </table>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(docs): enhance Matomo analytics tracking [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #36743:
URL: https://github.com/apache/superset/pull/36743#issuecomment-3671293901

   CodeAnt AI is reviewing your PR.
   
   ---
   
   ### Thanks for using CodeAnt! ๐ŸŽ‰
   
   We're free for open-source projects. if you're enjoying it, help us grow by sharing.
   
   [Share on X](https://twitter.com/intent/tweet?text=Just%20tried%20%40CodeAntAI%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos.%20Worth%20checking%20out%3A&url=https%3A//codeant.ai) ยท
   [Reddit](https://www.reddit.com/submit?title=Check%20out%20CodeAnt%20for%20automated%20code%20review&text=Just%20tried%20CodeAnt%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos.%20Worth%20checking%20out%3A%20https%3A//codeant.ai) ยท
   [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcodeant.ai&mini=true&title=Check%20out%20CodeAnt%20for%20automated%20code%20review&summary=Just%20tried%20CodeAnt%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(docs): enhance Matomo analytics tracking [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #36743:
URL: https://github.com/apache/superset/pull/36743


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(docs): enhance Matomo analytics tracking [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36743:
URL: https://github.com/apache/superset/pull/36743#issuecomment-3671294158

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(docs): enhance Matomo analytics tracking [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36743:
URL: https://github.com/apache/superset/pull/36743#discussion_r2631923339


##########
docs/src/theme/Root.js:
##########
@@ -27,10 +46,9 @@ export default function Root({ children }) {
     const { matomoUrl, matomoSiteId } = customFields;
 
     if (typeof window !== 'undefined') {
-      // Making testing easier, logging debug junk if we're in development
-      const devMode = window.location.hostname === 'localhost' ? true : false;
+      const devMode = window.location.hostname === 'localhost';

Review Comment:
   **Suggestion:** The `devMode` check only considers `localhost`, so when the docs are served from other common local hostnames like `127.0.0.1` or `::1`, full Matomo tracking will still run, leading to polluted analytics from local development sessions. [possible bug]
   
   **Severity Level:** Critical ๐Ÿšจ
   ```suggestion
         const devMode = ['localhost', '127.0.0.1', '0.0.0.0', '::1'].includes(
           window.location.hostname,
         );
   ```
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   Valid: many local dev setups use 127.0.0.1, ::1, or 0.0.0.0. Relying only on 'localhost' will allow tracking during local development in those cases, polluting analytics. Expanding the check to include common local hostnames/IPs prevents that and is low risk.
   </details>
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** docs/src/theme/Root.js
   **Line:** 49:49
   **Comment:**
   	*Possible Bug: The `devMode` check only considers `localhost`, so when the docs are served from other common local hostnames like `127.0.0.1` or `::1`, full Matomo tracking will still run, leading to polluted analytics from local development sessions.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   ```
   </details>



##########
docs/src/theme/Root.js:
##########
@@ -108,11 +218,19 @@ export default function Root({ children }) {
 
       window.addEventListener('popstate', handleRouteChange);

Review Comment:
   **Suggestion:** The Docusaurus route update listeners are added with anonymous callback functions but removed using `handleRouteChange`, which never matches the originally registered handlers, so the listeners persist after unmount and can cause duplicate page view tracking and memory leaks if the component is mounted/unmounted multiple times. [resource leak]
   
   **Severity Level:** Minor โš ๏ธ
   ```suggestion
         const routeUpdateHandlers = {};
   
         if (devMode) {
           console.log('Setting up Matomo tracking with enhanced features');
         }
   
         possibleEvents.forEach(eventName => {
           const handler = () => {
             if (devMode) {
               console.log(`Docusaurus route update detected via ${eventName}`);
             }
             handleRouteChange();
           };
           routeUpdateHandlers[eventName] = handler;
           document.addEventListener(eventName, handler);
         });
   
         // Cleanup
         return () => {
           possibleEvents.forEach(eventName => {
             const handler = routeUpdateHandlers[eventName];
             if (handler) {
               document.removeEventListener(eventName, handler);
             }
   ```
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   Correct: the code registers anonymous handler functions but attempts to remove them by passing handleRouteChange to removeEventListener, which will not match the original references. That causes listeners to persist across unmounts and can lead to duplicate tracking and memory leaks. The improved approach (store references and remove the same handlers) fixes a real resource-leak/behavior bug.
   </details>
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** docs/src/theme/Root.js
   **Line:** 198:219
   **Comment:**
   	*Resource Leak: The Docusaurus route update listeners are added with anonymous callback functions but removed using `handleRouteChange`, which never matches the originally registered handlers, so the listeners persist after unmount and can cause duplicate page view tracking and memory leaks if the component is mounted/unmounted multiple times.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   ```
   </details>



##########
docs/src/theme/Root.js:
##########
@@ -39,27 +57,121 @@ export default function Root({ children }) {
       window._paq.push(['setTrackerUrl', `${matomoUrl}/matomo.php`]);
       window._paq.push(['setSiteId', matomoSiteId]);
 
-      // Initial page view is handled by handleRouteChange
+      // Track downloads with custom extensions
+      window._paq.push(['setDownloadExtensions', DOWNLOAD_EXTENSIONS.join('|')]);
 
       // Now load the matomo.js script
       const script = document.createElement('script');
       script.async = true;
       script.src = `${matomoUrl}/matomo.js`;
       document.head.appendChild(script);
 
+      // Helper to track events
+      const trackEvent = (category, action, name, value) => {
+        if (devMode) {
+          console.log('Matomo trackEvent:', { category, action, name, value });
+        }
+        window._paq.push(['trackEvent', category, action, name, value]);
+      };
+
+      // Helper to track site search
+      const trackSiteSearch = (keyword, category, resultsCount) => {
+        if (devMode) {
+          console.log('Matomo trackSiteSearch:', { keyword, category, resultsCount });
+        }
+        window._paq.push(['trackSiteSearch', keyword, category, resultsCount]);
+      };
+
+      // Track external link clicks with categorization
+      const handleLinkClick = (event) => {
+        const link = event.target.closest('a');
+        if (!link) return;
+
+        const href = link.getAttribute('href');
+        if (!href) return;
+
+        try {
+          const url = new URL(href, window.location.origin);
+
+          // Skip internal links
+          if (url.hostname === window.location.hostname) return;
+
+          // Determine category based on domain
+          let category = 'External Link';
+          for (const [domain, cat] of Object.entries(EXTERNAL_LINK_CATEGORIES)) {
+            if (url.hostname.includes(domain)) {
+              category = cat;
+              break;
+            }
+          }
+
+          trackEvent('Outbound Link', category, href);
+        } catch {
+          // Invalid URL, skip tracking
+        }
+      };
+
+      // Track Algolia search queries
+      const setupAlgoliaTracking = () => {
+        // Watch for Algolia search modal
+        const observer = new MutationObserver((mutations) => {
+          mutations.forEach((mutation) => {
+            mutation.addedNodes.forEach((node) => {
+              if (node.nodeType === Node.ELEMENT_NODE) {
+                // Check for Algolia search input
+                const searchInput = node.querySelector?.('.DocSearch-Input') ||
+                                   (node.classList?.contains('DocSearch-Input') ? node : null);
+                if (searchInput) {
+                  let debounceTimer;
+                  searchInput.addEventListener('input', (e) => {
+                    clearTimeout(debounceTimer);
+                    debounceTimer = setTimeout(() => {
+                      const query = e.target.value.trim();
+                      if (query.length >= 3) {
+                        // Get result count if available
+                        const results = document.querySelectorAll('.DocSearch-Hit');
+                        trackSiteSearch(query, 'Documentation', results.length || false);

Review Comment:
   **Suggestion:** In the Algolia search tracking, using `results.length || false` incorrectly treats searches with zero results as "unknown result count" instead of 0, which skews the analytics data for Matomo site search reports. [logic error]
   
   **Severity Level:** Minor โš ๏ธ
   ```suggestion
                         trackSiteSearch(query, 'Documentation', results.length);
   ```
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   Accurate: results.length || false converts 0 to false which signals "unknown" rather than the actual 0 count. That skews Matomo analytics for zero-result queries. Passing results.length (an integer) preserves correct counts and is a straightforward fix.
   </details>
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** docs/src/theme/Root.js
   **Line:** 130:133
   **Comment:**
   	*Logic Error: In the Algolia search tracking, using `results.length || false` incorrectly treats searches with zero results as "unknown result count" instead of 0, which skews the analytics data for Matomo site search reports.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   ```
   </details>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(docs): enhance Matomo analytics tracking [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #36743:
URL: https://github.com/apache/superset/pull/36743#issuecomment-3671308047

   CodeAnt AI finished reviewing your PR.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org