Skip to content

Commit

Permalink
fix(widget): resolve conflict and update changelog
Browse files Browse the repository at this point in the history
  • Loading branch information
BilalMir135 committed Sep 9, 2023
2 parents be29e9e + 69b885e commit 34e3512
Show file tree
Hide file tree
Showing 11 changed files with 164 additions and 5 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- Revert the latest version back to 1.1.0 state.

## [1.3.0] - 2023-09-10

### Added

- Widget support through iframe.
- Pass events data into to widget.
- Custom widget on-click handling.
- Add engage data point.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "analytics-web3",
"version": "1.2.0",
"version": "1.3.0",
"description": "Spock analytics SDK analytics-web3 is a js module to collect and log all the data and events of DApp for analytics.",
"main": "dist/analytics-web3.min.js",
"license": "UNLICENSED",
Expand Down
2 changes: 2 additions & 0 deletions src/AnalyticsStorage/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { notUndefined } from '../utils/validators';
* @property {number} txnReject - total txn rejected in current session
* @property {number} txnSubmit - total txn submitted txn in current session
* @property {UserInfo|undefined} userInfo - user metadata
* @property {()=>number} sessionDuration - method to calculate current session duration
*/

/** @type {AnalyticsStore} */
Expand All @@ -48,6 +49,7 @@ const initialState = {
txnReject: 0,
txnSubmit: 0,
userInfo: undefined,
sessionDuration: () => 0,
};

class AnalyticsStorage {
Expand Down
25 changes: 24 additions & 1 deletion src/BaseAnalytics/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import AnalyticsStorage from '../AnalyticsStorage';
import { DEFAULT_CONFIG, LOG, TRACKING_EVENTS, STORAGE, UTM_KEYS, DATA_POINTS } from '../constants';
import { DEFAULT_CONFIG, LOG, TRACKING_EVENTS, STORAGE, UTM_KEYS, DATA_POINTS, withAlias } from '../constants';
import { cheapGuid, getQueryParams, parseFlowProperties, transformUTMKey } from './utils';
import { setCookie } from '../utils/cookies';
import { JSON_Formatter } from '../utils/formatting';
import { getConfig } from '../utils/helpers';
import { log } from '../utils/logs';
import Request from '../utils/request';

import WidgetController from '../Widget';

/**
* @typedef Config
* @type {object}
Expand Down Expand Up @@ -51,6 +53,8 @@ class BaseAnalytics {
testENV: this.testENV,
store: this.store,
});

this.widgetController = WidgetController;
}

/**
Expand Down Expand Up @@ -117,6 +121,25 @@ class BaseAnalytics {
this.dispatch({ trackingQueue: [...this.store.trackingQueue, { event, data }] });
}

if (this.dataPoints[DATA_POINTS.ENGAGE]) {
const { ip, flow, optOut, initialized, txnReject, txnSubmit, sessionDuration } = this.store;
this.widgetController.postMessage(withAlias(event.replace(/-/g, '_')), {
...data,
store: {
duration: typeof sessionDuration === 'function' ? sessionDuration() : 0,
flow,
initialized,
ip,
optOut,
txnReject,
txnSubmit,
},
browserProps: {
innerWidth: window.innerWidth,
},
});
}

logMessage && this.log(LOG.INFO, logMessage, data);
}

Expand Down
2 changes: 2 additions & 0 deletions src/Session/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ class Session extends BaseAnalytics {
this.hiddenTime = 0;
this.totalHiddenTime = 0;
this.hidden = 'hidden';

this.dispatch({ sessionDuration: this.sessionDuration.bind(this) });
}

trackSession() {
Expand Down
6 changes: 4 additions & 2 deletions src/WalletConnection/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ class WalletConnection extends BaseAnalytics {
logTransaction(status, txnObj, txnHash) {
if (status === 'rejected') {
const properties = { ...txnObj, status: 0 };
this.trackEvent({ event: TRACKING_EVENTS.TRANSACTION, properties, logMessage: 'Transaction rejected' });
this.dispatch({ txnReject: this.store.txnReject + 1 });
this.trackEvent({ event: TRACKING_EVENTS.TRANSACTION, properties, logMessage: 'Transaction rejected' });
} else if (status === 'submitted' && this.cacheTxnHash !== txnHash) {
const properties = { ...txnObj, hash: txnHash, status: 1 };
this.dispatch({ txnSubmit: this.store.txnSubmit + 1 });
this.trackEvent({ event: TRACKING_EVENTS.TRANSACTION, properties, logMessage: 'Transaction submitted' });
this.cacheTxnHash = txnHash;
this.dispatch({ txnSubmit: this.store.txnSubmit + 1 });
}
}

Expand Down Expand Up @@ -340,6 +340,8 @@ class WalletConnection extends BaseAnalytics {
const properties = { walletType };

this.trackEvent({ event: TRACKING_EVENTS.WALLET_CONNECTION, properties, logMessage: 'Wallet connect' });

// this.widgetController.postMessage(WIDGET_SEND_EVENTS.WALLET_CONNECT, { address: account?.toLowerCase(), chain });
}
}
}
Expand Down
93 changes: 93 additions & 0 deletions src/Widget/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { WIDGET_ENDPOINT, WIDGET_RECEIVE_EVENTS } from '../constants';
import { addEvent } from '../utils/helpers';

const iframwStyles = {
display: 'none',
position: 'fixed',
borderRadius: '0',
border: 'none',
zIndex: '2147483647',
};

function applyStyles(elemment, styles) {
for (const [cssProperty, value] of Object.entries(styles)) {
elemment.style[cssProperty] = value;
}
}

class WidgetController {
constructor() {
this.setUserDefinedOnClick = this.setUserDefinedOnClick.bind(this);
}

init(appKey) {
const createIframe = () => {
const iframe = document.createElement('iframe');
iframe.src = WIDGET_ENDPOINT + `/?appKey=${appKey}`;
iframe.title = 'Spock Widget';
iframe.id = 'spock-widget';
iframe.dataset.spockIframeLabel = new URL(WIDGET_ENDPOINT).host;
applyStyles(iframe, iframwStyles);
document.body.appendChild(iframe);
return iframe;
};

this.iframe = createIframe();

addEvent(window, 'message', this.eventHandler.bind(this));
}

eventHandler(event) {
const { origin, data } = event;
if (origin === WIDGET_ENDPOINT) {
switch (data?.message) {
case WIDGET_RECEIVE_EVENTS.SHOW_POPUP:
this.show(data?.body);
break;
case WIDGET_RECEIVE_EVENTS.HIDE_POPUP:
this.hide();
break;
case WIDGET_RECEIVE_EVENTS.BUTTON_CLICK:
this.hide();
if (data?.body?.redirectUrl) {
window.location.href = data?.body?.redirectUrl;
} else if (this.userDefinedClickMethod) {
this.userDefinedClickMethod(data?.body);
}
break;
default:
break;
}
}
}

async documentLoaded(counter) {
if (document.readyState != 'complete') {
await new Promise((resolve) => setTimeout(resolve, 5 * 1000));
//counter for protecting from infinite recursion
counter < 5 && (await this.documentLoaded(counter + 1));
}
}

async postMessage(message, body) {
if (this.iframe && this.iframe.contentWindow) {
//wait util document loading is complete
await this.documentLoaded(0);
this.iframe.contentWindow.postMessage({ message, body }, WIDGET_ENDPOINT);
}
}

show(styles) {
applyStyles(this.iframe, styles);
}

hide() {
this.iframe.style.display = 'none';
}

setUserDefinedOnClick(method) {
this.userDefinedClickMethod = method;
}
}

export default new WidgetController();
18 changes: 18 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ export const SERVER_ENDPOINT = 'https://ingest.spockanalytics.xyz';
*/
export const TEST_SERVER_ENDPOINT = 'https://ingest-dev.spockanalytics.xyz';

/**
* spock-widget hosting url
*/
export const WIDGET_ENDPOINT = 'https://widget.spockanalytics.xyz';

/**
* alias to make storage keys unqiue
*/
Expand All @@ -31,6 +36,7 @@ export const withAlias = (key) => `${ALIAS}_${key}`;
export const DATA_POINTS = {
BROWSER_PROFILE: 'browser_profile',
DEMOGRAPHICS: 'demographics',
ENGAGE: 'engage',
NAVIGATION: 'navigation',
UTM_PARAMS: 'utm_params',
WEB3: 'web3',
Expand Down Expand Up @@ -150,6 +156,18 @@ export const TRACKING_EVENTS = {
WALLET_CONNECTION: 'wallet-connect',
};

/**
* events received from widget
* SHOW_POPUP - show the popup to user
* HIDE_POPUP - close popup
* BUTTON_CLICK - onclick action
*/
export const WIDGET_RECEIVE_EVENTS = {
SHOW_POPUP: withAlias('show_popup'),
HIDE_POPUP: withAlias('hide_popup'),
BUTTON_CLICK: withAlias('button_click'),
};

/**
* constant for representing empty string
*/
Expand Down
4 changes: 4 additions & 0 deletions src/core/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ class Web3Analytics extends BaseAnalytics {
this.log(LOG.INFO, 'Web3 Analytics initialized');
this.userConsent();

if (this.dataPoints[DATA_POINTS.ENGAGE]) {
this.widgetController.init(this.appKey);
}

this.session.trackSession();
await this.userInfo.getUserInfo();
this.wallet.initialize();
Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Web3AnalyticsClass from './core';
import { EVENTS } from './constants';
import { addEvent } from './utils/helpers';
import WidgetController from './Widget';

function overrideLocalStorage() {
Storage.prototype._setItem = Storage.prototype.setItem;
Expand Down Expand Up @@ -43,6 +44,7 @@ Web3Analytics.init = function (config) {
Web3Analytics.trackPageView = web3AnalyticsInstance.trackPageView;
Web3Analytics.trackWalletConnection = web3AnalyticsInstance.wallet.trackWalletConnection;
Web3Analytics.walletProvider = web3AnalyticsInstance.wallet.walletProvider;
Web3Analytics.widgetOnClick = WidgetController.setUserDefinedOnClick;
};

export default Web3Analytics;
6 changes: 5 additions & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
declare type WidgetOnClickMethod = (params: { campaignId: string }) => void;

declare namespace Web3Analytics {
export function init(config: {
appKey: string;
dataPoints?: ('browser_profile' | 'demographics' | 'navigation' | 'utm_params' | 'web3')[];
dataPoints?: ('browser_profile' | 'demographics' | 'engage' | 'navigation' | 'utm_params' | 'web3')[];
debug?: boolean;
inactivityTimeout?: number;
optOut?: boolean;
Expand All @@ -20,6 +22,8 @@ declare namespace Web3Analytics {
export function trackWalletConnection(walletType: string, account: string, chainId: number): void;

export function walletProvider(provider: any): void;

export function widgetOnClick(method: WidgetOnClickMethod): void;
}

export default Web3Analytics;

0 comments on commit 34e3512

Please sign in to comment.