Skip to content

feat(replay): Add additional properties for UI clicks #7395

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

Merged
merged 16 commits into from
Mar 16, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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
18 changes: 18 additions & 0 deletions packages/integration-tests/suites/replay/clickBreadcrumbs/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;
window.Replay = new Sentry.Replay({
flushMinDelay: 500,
flushMaxDelay: 500,
useCompression: false,
blockAllMedia: false,
});

Sentry.init({
dsn: 'https://[email protected]/1337',
sampleRate: 0,
replaysSessionSampleRate: 1.0,
replaysOnErrorSampleRate: 0.0,

integrations: [window.Replay],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div role="button" id="error" class="btn btn-error" aria-label="An Error">An Error</div>
<button>
<img id="img"
alt="Alt Text"
/>
</button>
<button class="sentry-unmask" aria-label="Unmasked label">
Unmasked
</button>
</body>
</html>
103 changes: 103 additions & 0 deletions packages/integration-tests/suites/replay/clickBreadcrumbs/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { expect } from '@playwright/test';

import { sentryTest } from '../../../utils/fixtures';
import { expectedClickBreadcrumb } from '../../../utils/replayEventTemplates';
import { getReplayRecordingContent, shouldSkipReplayTest, waitForReplayRequest } from '../../../utils/replayHelpers';

for (let i = 0; i < 100; i++) {
sentryTest(
`replay should have correct click breadcrumbs${i}`,
async ({ forceFlushReplay, getLocalTestPath, page }) => {
if (shouldSkipReplayTest()) {
sentryTest.skip();
}

const reqPromise0 = waitForReplayRequest(page, 0);
const reqPromise1 = waitForReplayRequest(page, 1);

await page.route('https://dsn.ingest.sentry.io/**/*', route => {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

const url = await getLocalTestPath({ testDir: __dirname });

await page.goto(url);
await reqPromise0;

await page.click('#error');
await page.click('#img');
await page.click('.sentry-unmask');
await forceFlushReplay();
const req1 = await reqPromise1;
const content1 = getReplayRecordingContent(req1);
expect(content1.breadcrumbs).toEqual(
expect.arrayContaining([
{
...expectedClickBreadcrumb,
data: {
nodeId: expect.any(Number),
node: {
attributes: {
'aria-label': '** *****',
class: 'btn btn-error',
id: 'error',
role: 'button',
},
id: expect.any(Number),
tagName: 'div',
textContent: '** *****',
},
},
},
]),
);

expect(content1.breadcrumbs).toEqual(
expect.arrayContaining([
{
...expectedClickBreadcrumb,
data: {
nodeId: expect.any(Number),
node: {
attributes: {
alt: 'Alt Text',
id: 'img',
},
id: expect.any(Number),
tagName: 'img',
textContent: '',
},
},
},
]),
);

expect(content1.breadcrumbs).toEqual(
expect.arrayContaining([
{
...expectedClickBreadcrumb,
data: {
nodeId: expect.any(Number),
node: {
attributes: {
// TODO(rrweb): This is a bug in our rrweb fork!
// This attribute should be unmasked.
// 'aria-label': 'Unmasked label',
'aria-label': '******** *****',
class: 'sentry-unmask',
},
id: expect.any(Number),
tagName: 'button',
textContent: 'Unmasked',
},
},
},
]),
);
},
);
}
25 changes: 23 additions & 2 deletions packages/integration-tests/suites/replay/errors/errorMode/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,17 @@ sentryTest(
expect.arrayContaining([
{
...expectedClickBreadcrumb,
message: 'body > button#error',
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing this as it can leak attributes (e.g. aria label) that are masked with maskAllText

data: {
nodeId: expect.any(Number),
node: {
attributes: {
id: 'error',
},
id: expect.any(Number),
tagName: 'button',
textContent: '***** *****',
},
},
},
]),
);
Expand Down Expand Up @@ -131,7 +141,18 @@ sentryTest(

expect(content2.breadcrumbs).toEqual(
expect.arrayContaining([
{ ...expectedClickBreadcrumb, message: 'body > button#log' },
{
...expectedClickBreadcrumb,
data: {
node: {
attributes: { id: 'log' },
id: expect.any(Number),
tagName: 'button',
textContent: '*** ***** ** *** *******',
},
nodeId: expect.any(Number),
},
},
{ ...expectedConsoleBreadcrumb, level: 'log', message: 'Some message' },
]),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,22 @@ sentryTest(
);

expect(content1.breadcrumbs).toEqual(
expect.arrayContaining([{ ...expectedClickBreadcrumb, message: 'body > button#error' }]),
expect.arrayContaining([
{
...expectedClickBreadcrumb,
data: {
node: {
attributes: {
id: 'error',
},
id: expect.any(Number),
tagName: 'button',
textContent: '***** *****',
},
nodeId: expect.any(Number),
},
},
]),
);
},
);
Expand Down Expand Up @@ -108,7 +123,22 @@ sentryTest(

// The button click that triggered the error should still be recorded
expect(content1.breadcrumbs).toEqual(
expect.arrayContaining([{ ...expectedClickBreadcrumb, message: 'body > button#drop' }]),
expect.arrayContaining([
{
...expectedClickBreadcrumb,
data: {
node: {
attributes: {
id: 'drop',
},
id: expect.any(Number),
tagName: 'button',
textContent: '***** ***** *** **** **',
},
nodeId: expect.any(Number),
},
},
]),
);
},
);
9 changes: 8 additions & 1 deletion packages/integration-tests/utils/replayEventTemplates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,16 @@ export const expectedClickBreadcrumb = {
timestamp: expect.any(Number),
type: 'default',
category: 'ui.click',
message: expect.any(String),
data: {
nodeId: expect.any(Number),
node: {
attributes: {
id: expect.any(String),
},
id: expect.any(Number),
tagName: expect.any(String),
textContent: expect.any(String),
},
},
};

Expand Down
1 change: 1 addition & 0 deletions packages/replay/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"@babel/core": "^7.17.5",
"@sentry-internal/replay-worker": "7.43.0",
"@sentry-internal/rrweb": "1.105.0",
"@sentry-internal/rrweb-snapshot": "1.105.0",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imported a type and enum

"jsdom-worker": "^0.2.1",
"tslib": "^1.9.3"
},
Expand Down
43 changes: 29 additions & 14 deletions packages/replay/src/coreHandlers/handleDom.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { record } from '@sentry-internal/rrweb';
import type { INode } from '@sentry-internal/rrweb-snapshot';
import { NodeType } from '@sentry-internal/rrweb-snapshot';
import type { Breadcrumb } from '@sentry/types';
import { htmlTreeAsString } from '@sentry/utils';

import type { ReplayContainer } from '../types';
import { createBreadcrumb } from '../util/createBreadcrumb';
import { addBreadcrumbEvent } from './addBreadcrumbEvent';
import { getAttributesToRecord } from './util/getAttributesToRecord';

interface DomHandlerData {
name: string;
Expand All @@ -31,30 +32,44 @@ export const handleDomListener: (replay: ReplayContainer) => (handlerData: DomHa
* An event handler to react to DOM events.
*/
function handleDom(handlerData: DomHandlerData): Breadcrumb | null {
// Taken from https://github.com/getsentry/sentry-javascript/blob/master/packages/browser/src/integrations/breadcrumbs.ts#L112
let target;
let targetNode;
let targetNode: Node | INode | undefined;

// Accessing event.target can throw (see getsentry/raven-js#838, #768)
try {
targetNode = getTargetNode(handlerData);
target = htmlTreeAsString(targetNode);
} catch (e) {
target = '<unknown>';
// Nothing to do
}

if (target.length === 0) {
if (!targetNode) {
return null;
}

// `__sn` property is the serialized node created by rrweb
const serializedNode =
targetNode && '__sn' in targetNode && targetNode.__sn.type === NodeType.Element ? targetNode.__sn : null;

return createBreadcrumb({
category: `ui.${handlerData.name}`,
message: target,
data: {
// Not sure why this errors, Node should be correct (Argument of type 'Node' is not assignable to parameter of type 'INode')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...(targetNode ? { nodeId: record.mirror.getId(targetNode as any) } : {}),
},
data: serializedNode
? {
nodeId: serializedNode.id,
node: {
id: serializedNode.id,
tagName: serializedNode.tagName,
textContent: targetNode
? Array.from(targetNode.childNodes)
.map(
(node: Node | INode) => '__sn' in node && node.__sn.type === NodeType.Text && node.__sn.textContent,
)
.filter(Boolean) // filter out empty values
.map(text => (text as string).trim())
.join('')
: '',
attributes: getAttributesToRecord(serializedNode.attributes),
},
}
: {},
});
}

Expand Down
32 changes: 32 additions & 0 deletions packages/replay/src/coreHandlers/util/getAttributesToRecord.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Attributes we are interested in:
const ATTRIBUTES_TO_RECORD = new Set([
'id',
'class',
'aria-label',
'role',
'name',
'alt',
'title',
'data-test-id',
'data-testid',
]);

/**
* Inclusion list of attributes that we want to record from the DOM element
*/
export function getAttributesToRecord(attributes: Record<string, unknown>): Record<string, unknown> {
const obj: Record<string, unknown> = {};
for (const key in attributes) {
if (ATTRIBUTES_TO_RECORD.has(key)) {
let normalizedKey = key;

if (key === 'data-testid' || key === 'data-test-id') {
normalizedKey = 'testId';
}
Comment on lines +24 to +26
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ryan953 let's capture both and normal to testId?


obj[normalizedKey] = attributes[key];
}
}

return obj;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { getAttributesToRecord } from '../../../../src/coreHandlers/util/getAttributesToRecord';

it('records only included attributes', function () {
expect(
getAttributesToRecord({
id: 'foo',
classList: ['btn', 'btn-primary'],
}),
).toEqual({
id: 'foo',
classList: ['btn', 'btn-primary'],
});

expect(
getAttributesToRecord({
id: 'foo',
classList: ['btn', 'btn-primary'],
tabIndex: 2,
ariaDescribedBy: 'tooltip-1',
}),
).toEqual({
id: 'foo',
classList: ['btn', 'btn-primary'],
});

expect(
getAttributesToRecord({
tabIndex: 2,
ariaDescribedBy: 'tooltip-1',
}),
).toEqual({});
});