Skip to content

Commit

Permalink
Added Rudderstack tracking + fix classNames in js files (#1686)
Browse files Browse the repository at this point in the history
* added Rudderstack tracking + fix classNames in js files

* improved tracking of pages and make it silent
  • Loading branch information
gagdiez authored Jan 29, 2024
1 parent 63c64c4 commit 0e5ad43
Show file tree
Hide file tree
Showing 9 changed files with 205 additions and 45 deletions.
3 changes: 2 additions & 1 deletion website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@
"@near-wallet-selector/here-wallet": "^8.5.1",
"@near-wallet-selector/modal-ui": "^8.5.1",
"@near-wallet-selector/my-near-wallet": "^8.5.1",
"@rudderstack/analytics-js": "^3.0.0-beta.20",
"@saucelabs/theme-github-codeblock": "^0.2.3",
"algoliasearch": "^4.14.2",
"axios": "^1.6.2",
"bootstrap": "^5.3.2",
"bootstrap-icons": "^1.11.1",
"axios": "^1.6.2",
"clsx": "^1.1.1",
"docusaurus-plugin-remote-content": "^4.0.0",
"docusaurus-plugin-sass": "^0.2.5",
Expand Down
40 changes: 20 additions & 20 deletions website/src/components/ContactUs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,38 @@ If you have any questions, or simply would want to chat with us, please do throu

<br/>

<div class="container">
<div class="row">
<div class="col" style={{ '--ifm-col-width': '250px', marginBottom: '2em'}}>
<div class="avatar">
<div className="container">
<div className="row">
<div className="col" style={{ '--ifm-col-width': '250px', marginBottom: '2em'}}>
<div className="avatar">
<img
class="avatar__photo"
className="avatar__photo"
src={require("@site/static/docs/assets/home/twitter.png").default} />
<div class="avatar__intro">
<div class="avatar__name">Twitter</div>
<small class="avatar__subtitle"><a href="https://twitter.com/@nearprotocol">@nearprotocol</a></small>
<div className="avatar__intro">
<div className="avatar__name">Twitter</div>
<small className="avatar__subtitle"><a href="https://twitter.com/@nearprotocol">@nearprotocol</a></small>
</div>
</div>
</div>
<div class="col" style={{ '--ifm-col-width': '250px', marginBottom: '2em'}}>
<div class="avatar">
<div className="col" style={{ '--ifm-col-width': '250px', marginBottom: '2em'}}>
<div className="avatar">
<img
class="avatar__photo"
className="avatar__photo"
src={require("@site/static/docs/assets/home/discord.png").default} />
<div class="avatar__intro">
<div class="avatar__name">Discord</div>
<small class="avatar__subtitle"><a href="https://near.chat">NEAR Protocol</a></small>
<div className="avatar__intro">
<div className="avatar__name">Discord</div>
<small className="avatar__subtitle"><a href="https://near.chat">NEAR Protocol</a></small>
</div>
</div>
</div>
<div class="col" style={{ '--ifm-col-width': '250px', marginBottom: '2em'}}>
<div class="avatar">
<div className="col" style={{ '--ifm-col-width': '250px', marginBottom: '2em'}}>
<div className="avatar">
<img
class="avatar__photo"
className="avatar__photo"
src={require("@site/static/docs/assets/home/zulip.png").default} />
<div class="avatar__intro">
<div class="avatar__name">Zulip</div>
<small class="avatar__subtitle"><a href="https://near.zulipchat.com/">Near Chat</a></small>
<div className="avatar__intro">
<div className="avatar__name">Zulip</div>
<small className="avatar__subtitle"><a href="https://near.zulipchat.com/">Near Chat</a></small>
</div>
</div>
</div>
Expand Down
18 changes: 9 additions & 9 deletions website/src/components/featurelist.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import useDocusaurusContext from '@docusaurus/useDocusaurusContext';

export function FeatureList({ children }) {
return <>
<div class="container features">
<div class="row">
<div className="container features">
<div className="row">
{children}
</div>
</div>
Expand All @@ -13,7 +13,7 @@ export function FeatureList({ children }) {

export function Column({ title, children, size = 4 }) {
return <>
<div class={`col col--${size}`}>
<div className={`col col--${size}`}>
<h3>{title}</h3>
{children}
</div>
Expand All @@ -24,20 +24,20 @@ export function Feature({ image, title, subtitle, url, highlight = false }) {
const { siteConfig, i18n } = useDocusaurusContext();
let link;
if (url.startsWith('http')) {
link = <svg width="0.8rem" height="0.8rem" aria-hidden="true" viewBox="0 0 24 24" class="iconExternalLink_node_modules-@docusaurus-theme-classic-lib-theme-Icon-ExternalLink-styles-module"><path fill="currentColor" d="M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"></path></svg>;
link = <svg width="0.8rem" height="0.8rem" aria-hidden="true" viewBox="0 0 24 24" className="iconExternalLink_node_modules-@docusaurus-theme-classic-lib-theme-Icon-ExternalLink-styles-module"><path fill="currentColor" d="M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"></path></svg>;
} else if (i18n.currentLocale != i18n.defaultLocale) {
url = "/" + i18n.currentLocale + url;
}

return <>
<h4> </h4>
<a class="avatar" href={url} style={{ backgroundColor: highlight && "rgb(240, 255, 240)" }}>
<a className="avatar" href={url} style={{ backgroundColor: highlight && "rgb(240, 255, 240)" }}>
<img
class="avatar__photo"
className="avatar__photo"
src={require(`@site/static/docs/assets/welcome-pages/${image}`).default} />
<div class="avatar__intro">
<div class="avatar__name">{title} {link}</div>
<small class="avatar__subtitle">{subtitle}</small>
<div className="avatar__intro">
<div className="avatar__name">{title} {link}</div>
<small className="avatar__subtitle">{subtitle}</small>
</div>
</a>
</>
Expand Down
10 changes: 5 additions & 5 deletions website/src/components/social-widget.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from "react";
import { useWallet } from '@theme/Gateway/wallet-selector';
import { useWallet } from '@theme/scripts/wallet-selector';
import BrowserOnly from '@docusaurus/BrowserOnly';
import "react-bootstrap-typeahead/css/Typeahead.css";
import "react-bootstrap-typeahead/css/Typeahead.bs5.css";
Expand All @@ -25,7 +25,7 @@ export function WidgetEditor({ children, id = 1, height = "160px" }) {
}, [initNear, selector]);

return <div>
<div class="monaco">
<div className="monaco">
<MonacoEditor
height={height}
value={code}
Expand All @@ -47,9 +47,9 @@ export function WidgetEditor({ children, id = 1, height = "160px" }) {
/>
</div>

<div class="code_iframe">
<div class="bootstrap-scope">
<div class="vm-widget">
<div className="code_iframe">
<div className="bootstrap-scope">
<div className="vm-widget">
<Widget code={code} key={id} />
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion website/src/theme/NavbarItem/login-button.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { useState, useEffect } from 'react';
import { useWallet } from '@theme/Gateway/wallet-selector';
import { useWallet } from '@theme/scripts/wallet-selector';
import styles from './btn.module.css';

export default function LoginButton(props) {
Expand Down
24 changes: 15 additions & 9 deletions website/src/theme/Root.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,31 @@
import '@near-wallet-selector/modal-ui/styles.css';

import React from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser'; // https://docusaurus.io/docs/advanced/ssg#useisbrowser
import Gleap from "gleap"; // See https://gleap.io/docs/javascript/ and https://app.gleap.io/projects/62697858a4f6850036ae2e6a/widget
import { withRouter } from 'react-router-dom';
import useIsBrowser from '@docusaurus/useIsBrowser'; // https://docusaurus.io/docs/advanced/ssg#useisbrowser
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import { setupAlgoliaEvents } from './algolia-events';

import { useInitWallet } from './Gateway/wallet-selector';
import { setupAlgoliaEvents } from '@theme/scripts/algolia-events';
import { useInitWallet } from '@theme/scripts/wallet-selector';

const GLEAP_API_KEY = 'K2v3kvAJ5XtPzNYSgk4Ulpe5ptgBkIMv';

function Root({ children, history }) {
useInitWallet({ createAccessKeyFor: 'v1.social08.testnet' , networkId: 'testnet' });
function Root({ children, location, history }) {
useInitWallet({ createAccessKeyFor: 'v1.social08.testnet', networkId: 'testnet' });
const isBrowser = useIsBrowser();
const docusaurusContext = useDocusaurusContext();
if (isBrowser) {
Gleap.initialize(GLEAP_API_KEY);
const { initRudderAnalytics, recordPageView } = require('./scripts/rudderstack');

Gleap.initialize('K2v3kvAJ5XtPzNYSgk4Ulpe5ptgBkIMv');
setupAlgoliaEvents(docusaurusContext, history);

const rudderAnalytics = initRudderAnalytics();
recordPageView(rudderAnalytics, location.pathname);
}
return <>{children}</>;
}

export default withRouter(Root);
const router = withRouter(Root);


export default router;
File renamed without changes.
153 changes: 153 additions & 0 deletions website/src/theme/scripts/rudderstack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { nanoid } from 'nanoid';
import { createHash } from 'crypto';
import { get, split, truncate } from 'lodash';
import { RudderAnalytics } from '@rudderstack/analytics-js';

export function initRudderAnalytics() {
const rudderAnalytics = new RudderAnalytics();
window.rudderanalytics = rudderAnalytics;
rudderAnalytics.load("2bP8Ev07SiL1ABLXhcru4JZQ5Uh", "https://near.dataplane.rudderstack.com", {});
rudderAnalytics.setAnonymousId(getAnonymousId());
return rudderAnalytics;
}

export function recordPageView(rudderAnalytics, pageName) {
if(pageName === '/') return;
if(!rudderAnalytics) return;

// pageName should be /category/page and never contain ? or #
// but just in case we split on ? and #
const split = pageName.split('?')[0].split('#')[0].split('/');
const category = split[1];
const page = split.slice(2).join('/');
try {
rudderAnalytics.page(category, page, {
hashId: localStorage.getItem('hashId') || '',
url: filterURL(window.location.href),
ref: filterURL(document.referrer),
});
} catch (e) { } // Silent error
}

// let rudderAnalytics = null;
// let hashId = '';
// let pendingEvents = [];

// export function setAccountIdHash(accountId) {
// const hash = createHash('sha512');
// hash.update(accountId);
// hashId = hash.digest('hex');
// localStorage.setItem('hashId', hashId);
// }

export function getAnonymousId() {
const storageId = localStorage.getItem('anonymousUserId');

if (storageId) {
console.log("Existing storageId", storageId);
return storageId;
}

console.log("Creating new storageId");
const anonymousUserId = nanoid();
const anonymousUserIdCreatedAt = new Date().toUTCString();
localStorage.setItem('anonymousUserId', anonymousUserId);
localStorage.setItem('anonymousUserIdCreatedAt', anonymousUserIdCreatedAt);

return anonymousUserId;
}

function isStringAllowed(str) {
const denyList = ['account_id', 'public_key', 'all_keys', 'publicKey', 'apiKey', 'accountId', 'email'];
return !str || !denyList.some((param) => str.indexOf(param) !== -1);
}

function filterURL(url) {
const [urlTrim, params] = split(url, '?');
return isStringAllowed(params) ? url : urlTrim;
}


// const record = (eventType, e) => {
// const key = get(e.target, 'placeholder', get(e.target, 'innerText', get(e.target, 'href')));
// recordEventWithProps(eventType, {
// element: truncate(key, { length: 255 }),
// url: e.target ? filterURL(e.target.baseURI) : '',
// xPath: getXPath(e.target),
// componentSrc: getComponentName(e.target),
// });
// };

// export const recordClick = (e) => record('click', e);
// export const recordMouseEnter = (e) => record('mouseover', e);
// export const recordTouchStart = (e) => record('touchstart', e);

// export function recordWalletConnect(accountId) {
// if (!localStorage.getItem('hashId')) {
// setAccountIdHash(accountId);
// recordEvent('wallet-connected');
// }
// }

// export function reset() {
// if (!rudderAnalytics) return;
// try {
// recordEvent('wallet-logout');
// localStorage.removeItem('hashId');
// localStorage.removeItem('anonymousUserId');
// localStorage.removeItem('anonymousUserIdCreatedAt');
// rudderAnalytics.reset();
// } catch (e) {
// console.error(e);
// }
// }

// export function recordEventWithProps(eventLabel, properties) {
// if (!rudderAnalytics) return;
// try {
// rudderAnalytics.track(eventLabel, {
// ...properties,
// hashId: localStorage.getItem('hashId'),
// anonymousUserIdCreatedAt,
// });
// } catch (e) {
// console.error(e);
// }
// }

// export function recordEvent(eventLabel) {
// if (!rudderAnalytics) return;
// try {
// rudderAnalytics.track(eventLabel, {
// hashId: localStorage.getItem('hashId'),
// url: window.location.href,
// anonymousUserIdCreatedAt,
// });
// } catch (e) {
// console.error(e);
// }
// }

// function getComponentName(element) {
// if (!element) return '';
// if (element.hasAttribute('data-component')) return element.getAttribute('data-component') || '';
// return '';
// }

// function getXPath(element) {
// if (!element) return '';
// if (element.id !== '') return 'id("' + element.id + '")';
// if (element === document.body) return element.tagName;

// let ix = 0;
// const siblings = element.parentNode?.children;
// if (!siblings) return '';

// for (let i = 0; i < siblings.length; i++) {
// const sibling = siblings[i];
// if (sibling === element) return getXPath(element.parentElement) + '/' + element.tagName + '[' + (ix + 1) + ']';
// if (sibling.nodeType === 1 && sibling.tagName === element.tagName) ix++;
// }

// return '';
// }

0 comments on commit 0e5ad43

Please sign in to comment.