Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update auto tracking plugin #589

Merged
merged 3 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/plugin-auto-tracking-browser/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ module.exports = {
rootDir: '.',
testEnvironment: 'jsdom',
coveragePathIgnorePatterns: ['index.ts'],
};
setupFiles: ['./test/setup.ts'],
};

1 change: 1 addition & 0 deletions packages/plugin-auto-tracking-browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"@rollup/plugin-commonjs": "^23.0.4",
"@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-typescript": "^10.0.1",
"css.escape": "^1.5.1",
"rollup": "^2.79.1",
"rollup-plugin-execute": "^1.1.1",
"rollup-plugin-gzip": "^3.1.0",
Expand Down
41 changes: 35 additions & 6 deletions packages/plugin-auto-tracking-browser/src/auto-tracking-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
/* eslint-disable no-restricted-globals */
import { BrowserClient, BrowserConfig, EnrichmentPlugin } from '@amplitude/analytics-types';
import * as constants from './constants';
import { getText } from './helpers';
import { getText, isPageUrlAllowed, getAttributesWithPrefix, removeEmptyProperties } from './helpers';
import { finder } from './libs/finder';

type BrowserEnrichmentPlugin = EnrichmentPlugin<BrowserClient, BrowserConfig>;
type ActionType = 'click' | 'change';
type AllowedTag = 'a' | 'button' | 'input' | 'select' | 'textarea' | 'label';

const DEFAULT_TAG_ALLOWLIST = ['a', 'button', 'input', 'select', 'textarea', 'label'];
const DEFAULT_DATA_ATTRIBUTE_PREFIX = 'data-amp-auto-track-';
justin-fiedler marked this conversation as resolved.
Show resolved Hide resolved

interface EventListener {
element: Element;
Expand All @@ -15,12 +18,21 @@ interface EventListener {
}

interface Options {
tagAllowlist?: AllowedTag[];
cssSelectorAllowlist?: string[];
justin-fiedler marked this conversation as resolved.
Show resolved Hide resolved
tagAllowlist?: string[];
pageUrlAllowlist?: string[];
shouldTrackEventCallback?: (actionType: ActionType, element: Element) => boolean;
dataAttributePrefix?: string;
}

export const autoTrackingPlugin = (options: Options = {}): BrowserEnrichmentPlugin => {
const { tagAllowlist = DEFAULT_TAG_ALLOWLIST, cssSelectorAllowlist } = options;
const {
tagAllowlist = DEFAULT_TAG_ALLOWLIST,
cssSelectorAllowlist,
liuyang1520 marked this conversation as resolved.
Show resolved Hide resolved
pageUrlAllowlist,
shouldTrackEventCallback,
dataAttributePrefix = DEFAULT_DATA_ATTRIBUTE_PREFIX,
} = options;
const name = constants.PLUGIN_NAME;
const type = 'enrichment';

Expand Down Expand Up @@ -52,6 +64,15 @@ export const autoTrackingPlugin = (options: Options = {}): BrowserEnrichmentPlug
if (!element) {
return false;
}

if (shouldTrackEventCallback) {
return shouldTrackEventCallback(actionType, element);
justin-fiedler marked this conversation as resolved.
Show resolved Hide resolved
}

if (!isPageUrlAllowed(window.location.href, pageUrlAllowlist)) {
return false;
}

/* istanbul ignore next */
const elementType = (element as HTMLInputElement)?.type || '';
if (typeof elementType === 'string') {
Expand All @@ -62,9 +83,11 @@ export const autoTrackingPlugin = (options: Options = {}): BrowserEnrichmentPlug
return false;
}
}
const tag = element.tagName.toLowerCase();
/* istanbul ignore next */
const tag = element?.tagName?.toLowerCase?.();
/* istanbul ignore if */
if (!tagAllowlist.includes(tag)) {
if (!DEFAULT_TAG_ALLOWLIST.includes(tag) || !tagAllowlist.includes(tag)) {
// Tag needs to be in the default allowlist and the user provided allowlist.
return false;
}
if (cssSelectorAllowlist) {
justin-fiedler marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -95,6 +118,9 @@ export const autoTrackingPlugin = (options: Options = {}): BrowserEnrichmentPlug
/* istanbul ignore next */
const rect =
typeof element.getBoundingClientRect === 'function' ? element.getBoundingClientRect() : { left: null, top: null };
const ariaLabel = element.getAttribute('aria-label');
const attributes = getAttributesWithPrefix(element, dataAttributePrefix);
const selector = finder(element);
/* istanbul ignore next */
const properties: Record<string, any> = {
[constants.AMPLITUDE_EVENT_PROP_ELEMENT_ID]: element.id,
Expand All @@ -103,6 +129,9 @@ export const autoTrackingPlugin = (options: Options = {}): BrowserEnrichmentPlug
[constants.AMPLITUDE_EVENT_PROP_ELEMENT_TEXT]: getText(element),
[constants.AMPLITUDE_EVENT_PROP_ELEMENT_POSITION_LEFT]: rect.left == null ? null : Math.round(rect.left),
[constants.AMPLITUDE_EVENT_PROP_ELEMENT_POSITION_TOP]: rect.top == null ? null : Math.round(rect.top),
[constants.AMPLITUDE_EVENT_PROP_ELEMENT_ARIA_LABEL]: ariaLabel,
[constants.AMPLITUDE_EVENT_PROP_ELEMENT_ATTRIBUTES]: attributes,
[constants.AMPLITUDE_EVENT_PROP_ELEMENT_SELECTOR]: selector,
[constants.AMPLITUDE_EVENT_PROP_PAGE_URL]: window.location.href.split('?')[0],
[constants.AMPLITUDE_EVENT_PROP_PAGE_TITLE]: (typeof document !== 'undefined' && document.title) || '',
[constants.AMPLITUDE_EVENT_PROP_VIEWPORT_HEIGHT]: window.innerHeight,
Expand All @@ -111,7 +140,7 @@ export const autoTrackingPlugin = (options: Options = {}): BrowserEnrichmentPlug
if (tag === 'a' && actionType === 'click' && element instanceof HTMLAnchorElement) {
properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_HREF] = element.href;
}
return properties;
return removeEmptyProperties(properties);
};

const setup: BrowserEnrichmentPlugin['setup'] = async (config, amplitude) => {
Expand Down
3 changes: 3 additions & 0 deletions packages/plugin-auto-tracking-browser/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export const AMPLITUDE_EVENT_PROP_ELEMENT_TEXT = '[Amplitude] Element Text';
export const AMPLITUDE_EVENT_PROP_ELEMENT_HREF = '[Amplitude] Element Href';
export const AMPLITUDE_EVENT_PROP_ELEMENT_POSITION_LEFT = '[Amplitude] Element Position Left';
export const AMPLITUDE_EVENT_PROP_ELEMENT_POSITION_TOP = '[Amplitude] Element Position Top';
export const AMPLITUDE_EVENT_PROP_ELEMENT_ARIA_LABEL = '[Amplitude] Element Aria Label';
export const AMPLITUDE_EVENT_PROP_ELEMENT_ATTRIBUTES = '[Amplitude] Element Attributes';
export const AMPLITUDE_EVENT_PROP_ELEMENT_SELECTOR = '[Amplitude] Element Selector';
export const AMPLITUDE_EVENT_PROP_PAGE_URL = '[Amplitude] Page URL';
export const AMPLITUDE_EVENT_PROP_PAGE_TITLE = '[Amplitude] Page Title';
export const AMPLITUDE_EVENT_PROP_VIEWPORT_HEIGHT = '[Amplitude] Viewport Height';
Expand Down
42 changes: 42 additions & 0 deletions packages/plugin-auto-tracking-browser/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,45 @@ export const getText = (element: Element): string => {
}
return text;
};

export const isPageUrlAllowed = (url: string, pageUrlAllowlist: string[] | undefined) => {
justin-fiedler marked this conversation as resolved.
Show resolved Hide resolved
if (!pageUrlAllowlist || !pageUrlAllowlist.length) {
liuyang1520 marked this conversation as resolved.
Show resolved Hide resolved
return true;
}
return pageUrlAllowlist.some((allowedUrl) => {
const allowedUrlRegex = new RegExp(allowedUrl);
liuyang1520 marked this conversation as resolved.
Show resolved Hide resolved
return url.match(allowedUrlRegex);
});
};

export const getAttributesWithPrefix = (element: Element, prefix: string): { [key: string]: string } => {
return element.getAttributeNames().reduce((attributes: { [key: string]: string }, attributeName) => {
if (attributeName.startsWith(prefix)) {
const attributeKey = attributeName.replace(prefix, '');
const attributeValue = element.getAttribute(attributeName);
if (attributeKey) {
attributes[attributeKey] = attributeValue || '';
}
}
return attributes;
}, {});
};

export const isEmpty = (value: unknown) => {
return (
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0)
);
};

export const removeEmptyProperties = (properties: { [key: string]: unknown }) => {
return Object.keys(properties).reduce((filteredProperties: { [key: string]: unknown }, key) => {
const value = properties[key];
if (!isEmpty(value)) {
filteredProperties[key] = value;
}
return filteredProperties;
}, {});
};
Loading