Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions packages/analytics-browser/test/config/joined-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,32 @@ describe('joined-config', () => {
expect(elementInteractions).not.toHaveProperty('pageUrlAllowlistRegex');
});

describe('clickCell', () => {
const applyRemoteClickCell = (clickCell: unknown) => {
localConfig = createConfigurationMock({});
updateBrowserConfigWithRemoteConfig({ autocapture: { elementInteractions: { clickCell } } }, localConfig);
expectIsAutocaptureObjectWithElementInteractions(localConfig);
return localConfig.autocapture.elementInteractions.clickCell;
};

test('should deliver a remote `enabled: false` as false', () => {
expect(applyRemoteClickCell({ enabled: false })).toBe(false);
expect(applyRemoteClickCell({ enabled: false, minCellSizePx: 32, maxCellsPerAxis: 5 })).toBe(false);
});

test('should deliver a remote enabled-only object as true', () => {
expect(applyRemoteClickCell({ enabled: true })).toBe(true);
});

test('should deliver the grid parameters of an enabled remote object', () => {
expect(applyRemoteClickCell({ enabled: true, minCellSizePx: 32, maxCellsPerAxis: 5 })).toEqual({
minCellSizePx: 32,
maxCellsPerAxis: 5,
});
expect(applyRemoteClickCell({ minCellSizePx: 32 })).toEqual({ minCellSizePx: 32 });
});
});

describe('networkTracking', () => {
describe('headers', () => {
test('should translate responseHeaders and requestHeaders to local responseHeaders and requestHeaders', () => {
Expand Down
37 changes: 37 additions & 0 deletions packages/analytics-core/src/types/element-interactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,43 @@ export interface ElementInteractionsOptions {
* is true. Default is 1. Clamped into [1, 10].
*/
maxShadowDomDepth?: number;

/**
* Records where inside the clicked element a pointer click landed. A grid is
* laid over the element's bounding box and the cell under the pointer is sent
* on `[Amplitude] Element Clicked` as `[Amplitude] Element Click Cell`,
* formatted `<cols>x<rows>:<col>,<row>` (zero-based, from the top-left),
* e.g. `4x3:2,1`. The grid parameters in effect are sent with it as
* `[Amplitude] Element Click Cell Min Size` and
* `[Amplitude] Element Click Cell Max Per Axis`.
*
* Set to `false` to send none of these properties.
* Set to `true` or an options object to send them with default or custom grid parameters.
* Default is true.
*
* Applied at plugin initialization.
*/
clickCell?: boolean | ClickCellOptions;
}

export interface ClickCellOptions {
/**
* Whether the click cell properties are sent.
* Default is true.
*/
enabled?: boolean;
/**
* Minimum width and height of a grid cell, in CSS pixels. The grid has
* `clamp(floor(size / minCellSizePx), 1, maxCellsPerAxis)` cells on each axis,
* so an element smaller than twice this size on an axis gets one cell on that axis.
* Default is 64. Values that are not a positive number fall back to the default.
*/
minCellSizePx?: number;
/**
* Largest number of cells along one axis. Fractional values are rounded down.
* Default is 10. Values below 1 fall back to the default.
*/
maxCellsPerAxis?: number;
}

type MatchingCondition = {
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-autocapture-browser/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ Examples:
|`pageUrlExcludelist`|`(string\|RegExp)[]`|`undefined`| When provided, block tracking on elements matching URLs. Takes precedence over allowlist. |
|`shouldTrackEventResolver`|`(actionType: ActionType, element: Element) => boolean`|`undefined`| When provided, overwrite all other allowlists and configurations. |
|`dataAttributePrefix`|`string`|`'data-amp-track-'`| Allow data attributes to be collected in event property. |
|`clickCell`|`boolean \| { enabled?: boolean; minCellSizePx?: number; maxCellsPerAxis?: number }`|`true`| Send where inside the clicked element a pointer click landed, as `[Amplitude] Element Click Cell` (`<cols>x<rows>:<col>,<row>`, the cell of a grid laid over the element), with the grid parameters in effect as `[Amplitude] Element Click Cell Min Size` (default `64`) and `[Amplitude] Element Click Cell Max Per Axis` (default `10`). Set to `false` to send none of them. |

### 3. Install plugin to Amplitude SDK

Expand Down
28 changes: 19 additions & 9 deletions packages/plugin-autocapture-browser/src/autocapture-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ import {
type ElementBasedTimestampedEvent,
type TimestampedEvent,
type NavigateEvent,
getClickCellProperties,
getNormalizedPageUrl,
normalizePageUrl,
resolveClickCellConfig,
resolveHistoryNavigationUrl,
} from './helpers';
import { enableVisualTagging } from './libs/messenger';
Expand Down Expand Up @@ -147,6 +149,7 @@ export const autocapturePlugin = (
const subscriptions: Unsubscribable[] = [];

const dataExtractor = new DataExtractor(options, context);
const clickCellConfig = resolveClickCellConfig(options.clickCell);

// Page-level state shared across trackers, emitted in a single Page View End event on beforeunload
// elementExposedForPage holds the total set of elements seen during the entire page view lifetime
Expand All @@ -161,15 +164,21 @@ export const autocapturePlugin = (

const createObservables = (): AllWindowObservables => {
const clickObservable = multicast(
createClickObservable().map(
(click) =>
dataExtractor.addAdditionalEventProperties(
click,
'click',
(options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,
dataAttributePrefix,
) as ElementBasedTimestampedEvent<MouseEvent>,
),
createClickObservable().map((click) => {
const enrichedClick = dataExtractor.addAdditionalEventProperties(
click,
'click',
(options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,
dataAttributePrefix,
) as ElementBasedTimestampedEvent<MouseEvent>;
// Read here, while the element is still laid out as it was when clicked.
enrichedClick.clickCellProperties = getClickCellProperties(
enrichedClick.event,
enrichedClick.closestTrackedAncestor,
clickCellConfig,
);
return enrichedClick;
}),
);

const changeObservable = multicast(
Expand Down Expand Up @@ -358,6 +367,7 @@ export const autocapturePlugin = (
allObservables,
options: options as AutoCaptureOptionsWithDefaults,
getEventProperties: (...args) => dataExtractor.getEventProperties(...args, dataAttributePrefix),
clickCellConfig,
amplitude,
shouldTrackEvent,
shouldTrackActionClick: shouldTrackActionClick,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { AllWindowObservables, AutoCaptureOptionsWithDefaults } from '../autocapture-plugin';
import { BrowserClient, ActionType, merge, asyncMap } from '@amplitude/analytics-core';
import {
type ClickCellConfig,
ElementBasedTimestampedEvent,
filterOutNonTrackableEvents,
getClickCellProperties,
getClosestElement,
shouldTrackEvent,
TimestampedEvent,
Expand All @@ -14,13 +16,15 @@ export function trackActionClick({
allObservables,
options,
getEventProperties,
clickCellConfig,
shouldTrackEvent,
shouldTrackActionClick,
}: {
amplitude: BrowserClient;
allObservables: AllWindowObservables;
options: AutoCaptureOptionsWithDefaults;
getEventProperties: (actionType: ActionType, element: Element) => Record<string, any>;
clickCellConfig: ClickCellConfig | null;
shouldTrackActionClick: shouldTrackEvent;
shouldTrackEvent: shouldTrackEvent;
}) {
Expand All @@ -39,6 +43,9 @@ export function trackActionClick({
if (click.closestTrackedAncestor !== null) {
click.targetElementProperties = getEventProperties(click.type, click.closestTrackedAncestor);
}
// The event is tracked only after a mutation or navigation follows the click, by which
// time the element may have moved, resized or left the page. Read the click cell now.
click.clickCellProperties = getClickCellProperties(click.event, click.closestTrackedAncestor, clickCellConfig);
return click;
})
.filter(filterOutNonTrackableEvents)
Expand Down Expand Up @@ -83,10 +90,12 @@ export function trackActionClick({

return actionClickObservable.subscribe((actionClick) => {
if (!actionClick) return;
const click = actionClick as ElementBasedTimestampedEvent<MouseEvent>;
/* istanbul ignore next */
amplitude?.track(
AMPLITUDE_ELEMENT_CLICKED_EVENT,
getEventProperties('click', (actionClick as ElementBasedTimestampedEvent<MouseEvent>).closestTrackedAncestor),
);
amplitude?.track(AMPLITUDE_ELEMENT_CLICKED_EVENT, {
...getEventProperties('click', click.closestTrackedAncestor),
// Pointer position within the clicked element, read when the click was captured.
...click.clickCellProperties,
});
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ export function trackClicks({

return clicks.subscribe((click: ElementBasedTimestampedEvent<ElementBasedEvent>) => {
/* istanbul ignore next */
amplitude?.track(AMPLITUDE_ELEMENT_CLICKED_EVENT, click.targetElementProperties);
amplitude?.track(AMPLITUDE_ELEMENT_CLICKED_EVENT, {
...click.targetElementProperties,
// Pointer position within the clicked element, read when the click was captured.
...click.clickCellProperties,
});
});
}
12 changes: 12 additions & 0 deletions packages/plugin-autocapture-browser/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ export const AMPLITUDE_EVENT_PROP_ELEMENT_HIERARCHY = '[Amplitude] Element Hiera
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';
/**
* Where inside the clicked element the pointer was: the cell of a grid laid over the
* element's bounding box, formatted `<cols>x<rows>:<col>,<row>` (zero-based from the top-left).
*/
export const AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL = '[Amplitude] Element Click Cell';
/** Minimum grid cell size, in CSS pixels, in effect when the click cell was computed. */
export const AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL_MIN_SIZE = '[Amplitude] Element Click Cell Min Size';
/** Largest number of grid cells per axis in effect when the click cell was computed. */
export const AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL_MAX_PER_AXIS = '[Amplitude] Element Click Cell Max Per Axis';
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_PATH = '[Amplitude] Element Path';
Expand Down Expand Up @@ -55,6 +64,9 @@ export const DATA_AMP_MASK_ATTRIBUTES = 'data-amp-mask-attributes';

export const DATA_AMP_INTERNAL_SHADOW = 'data-amp-internal-shadow';

export const DEFAULT_CLICK_CELL_MIN_SIZE_PX = 64;
export const DEFAULT_CLICK_CELL_MAX_PER_AXIS = 10;

export const MAX_MASK_TEXT_PATTERNS = 25;

export const MAX_ATTRIBUTE_LENGTH = 128;
Expand Down
112 changes: 112 additions & 0 deletions packages/plugin-autocapture-browser/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import {
} from '@amplitude/analytics-core';
import { collectOpenShadowRoots, segmentWalk, walkComposedAncestors } from '@amplitude/element-selector';
import { SHADOW_OFF, type ShadowMode } from './shadow-mode';
import {
AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL,
AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL_MAX_PER_AXIS,
AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL_MIN_SIZE,
DEFAULT_CLICK_CELL_MAX_PER_AXIS,
DEFAULT_CLICK_CELL_MIN_SIZE_PX,
} from './constants';

export type JSONValue = string | number | boolean | null | { [x: string]: JSONValue } | Array<JSONValue>;

Expand Down Expand Up @@ -352,6 +359,105 @@ export function generateUniqueId(): string {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}

const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && isFinite(value);

/**
* Whether a click came from a pointer. Keyboard activations and programmatic
* `element.click()` calls dispatch a click with `detail === 0`, and plain
* `Event`s have no `detail`; neither has a real pointer position.
*/
const isPointerClick = (event: Event | MouseEvent | null | undefined): event is MouseEvent =>
!!event && typeof (event as MouseEvent).detail === 'number' && (event as MouseEvent).detail !== 0;

/** Grid parameters for the click cell, with defaults applied. */
export type ClickCellConfig = {
/** Minimum width and height of a grid cell, in CSS pixels. */
minCellSizePx: number;
/** Largest number of cells along one axis. */
maxCellsPerAxis: number;
};

type ClickCellOptions = Exclude<ElementInteractionsOptions['clickCell'], boolean | undefined>;

/**
* Resolves the `clickCell` option into the grid parameters to use, or `null`
* when the click cell is disabled. Unusable grid parameters fall back to the defaults.
*
* Disabled is either `false` or `{ enabled: false }`. Remote config delivers
* `{ enabled: false }` as `false` and `{ enabled: true }` as `true`
* (see `translateRemoteConfigToLocal`), so both forms have to be honoured.
*/
export const resolveClickCellConfig = (options: ElementInteractionsOptions['clickCell']): ClickCellConfig | null => {
if (options === false) {
return null;
}
const gridOptions: ClickCellOptions = typeof options === 'object' && options !== null ? options : {};
if (gridOptions.enabled === false) {
return null;
}
const { minCellSizePx, maxCellsPerAxis } = gridOptions;
return {
minCellSizePx: isFiniteNumber(minCellSizePx) && minCellSizePx > 0 ? minCellSizePx : DEFAULT_CLICK_CELL_MIN_SIZE_PX,
maxCellsPerAxis:
isFiniteNumber(maxCellsPerAxis) && maxCellsPerAxis >= 1
? Math.floor(maxCellsPerAxis)
: DEFAULT_CLICK_CELL_MAX_PER_AXIS,
};
};

const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));

/**
* Returns where inside `element` a pointer click landed, keyed by the click
* cell event property names.
*
* A grid is laid over the element's bounding box, sized per axis as
* `clamp(floor(size / minCellSizePx), 1, maxCellsPerAxis)`, and the cell under
* the pointer is reported as `<cols>x<rows>:<col>,<row>` (zero-based from the
* top-left). The value carries its own grid so it stays readable when the grid
* parameters change. A click outside the box (a descendant that overflows it)
* is assigned to the nearest edge cell.
*
* Must be called while the element is still laid out as it was when the click
* happened: it reads the element's current bounding box.
*
* Returns an empty object when the click cell is disabled (`config` is null),
* the click has no pointer position, or the element has no size. It never
* throws: it runs in the click capture path, where an error would end click
* tracking for the page.
*/
export const getClickCellProperties = (
event: Event | MouseEvent | null | undefined,
element: Element | null | undefined,
config: ClickCellConfig | null,
): Record<string, string | number> => {
if (!config || !isPointerClick(event) || typeof element?.getBoundingClientRect !== 'function') {
return {};
}
const { clientX, clientY } = event;
if (!isFiniteNumber(clientX) || !isFiniteNumber(clientY)) {
return {};
}
try {
const rect = element.getBoundingClientRect();
if (!isFiniteNumber(rect.width) || !isFiniteNumber(rect.height) || rect.width <= 0 || rect.height <= 0) {
return {};
}
const { minCellSizePx, maxCellsPerAxis } = config;
const cols = clamp(Math.floor(rect.width / minCellSizePx), 1, maxCellsPerAxis);
const rows = clamp(Math.floor(rect.height / minCellSizePx), 1, maxCellsPerAxis);
const col = clamp(Math.floor(((clientX - rect.left) / rect.width) * cols), 0, cols - 1);
const row = clamp(Math.floor(((clientY - rect.top) / rect.height) * rows), 0, rows - 1);
return {
[AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL]: `${cols}x${rows}:${col},${row}`,
[AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL_MIN_SIZE]: minCellSizePx,
[AMPLITUDE_EVENT_PROP_ELEMENT_CLICK_CELL_MAX_PER_AXIS]: maxCellsPerAxis,
};
} catch {
return {};
}
};

export const filterOutNonTrackableEvents = (event: ElementBasedTimestampedEvent<ElementBasedEvent>): boolean => {
// Filter out changeEvent events with no target
// This could happen when change events are triggered programmatically
Expand Down Expand Up @@ -381,6 +487,12 @@ export type ElementBasedTimestampedEvent<T> = BaseTimestampedEvent<T> & {
type: 'click' | 'change';
closestTrackedAncestor: Element;
targetElementProperties: Record<string, any>;
/**
* Click cell properties of `closestTrackedAncestor`, read when the click was
* captured. Kept apart from `targetElementProperties` because action clicks
* are tracked later, after the element may have moved or resized.
*/
clickCellProperties?: Record<string, string | number>;
};

export type evaluateTriggersFn = (
Expand Down
Loading
Loading