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(utils): Prioritize Component name attributes over HTML Tree String #9496

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from 9 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
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
<body>
<button id="button1" type="button">Button 1</button>
<button id="button2" type="button">Button 2</button>
<button id="annotated-button" type="button" data-component="AnnotatedButton">Button 2</button>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,38 @@ sentryTest('captures Breadcrumb for clicks & debounces them for a second', async
},
]);
});

sentryTest(
'prioritizes the annotated component name within the breadcrumb message',
async ({ getLocalTestUrl, page }) => {
const url = await getLocalTestUrl({ testDir: __dirname });

await page.route('**/foo', route => {
return route.fulfill({
status: 200,
body: JSON.stringify({
userNames: ['John', 'Jane'],
}),
headers: {
'Content-Type': 'application/json',
},
});
});

const promise = getFirstSentryEnvelopeRequest<Event>(page);

await page.goto(url);
await page.click('#annotated-button');
await page.evaluate('Sentry.captureException("test exception")');

const eventData = await promise;

expect(eventData.breadcrumbs).toEqual([
{
timestamp: expect.any(Number),
category: 'ui.click',
message: 'AnnotatedButton',
},
]);
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@
<body>
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="annotated-input" data-component="AnnotatedInput" type="text" />
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,46 @@ sentryTest('captures Breadcrumb for events on inputs & debounced them', async ({
},
]);
});

sentryTest(
'prioritizes the annotated component name within the breadcrumb message',
async ({ getLocalTestUrl, page }) => {
const url = await getLocalTestUrl({ testDir: __dirname });

await page.route('**/foo', route => {
return route.fulfill({
status: 200,
body: JSON.stringify({
userNames: ['John', 'Jane'],
}),
headers: {
'Content-Type': 'application/json',
},
});
});

const promise = getFirstSentryEnvelopeRequest<Event>(page);

await page.goto(url);

await page.click('#annotated-input');
await page.type('#annotated-input', 'John', { delay: 1 });

await page.evaluate('Sentry.captureException("test exception")');
const eventData = await promise;
expect(eventData.exception?.values).toHaveLength(1);

expect(eventData.breadcrumbs).toEqual([
{
timestamp: expect.any(Number),
category: 'ui.click',
message: 'AnnotatedInput',
},
{
timestamp: expect.any(Number),
category: 'ui.input',
message: 'AnnotatedInput',
},
]);
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ const delay = e => {
};

document.querySelector('[data-test-id=interaction-button]').addEventListener('click', delay);
document.querySelector('[data-test-id=annotated-button]').addEventListener('click', delay);
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<body>
<div>Rendered Before Long Task</div>
<button data-test-id="interaction-button">Click Me</button>
<button data-test-id="annotated-button" data-component="AnnotatedButton">Click Me</button>
<script src="https://example.com/path/to/script.js"></script>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,35 @@ sentryTest(
}
},
);

sentryTest(
'should use the component name for a clicked element when it is available',
async ({ browserName, getLocalTestPath, page }) => {
const supportedBrowsers = ['chromium', 'firefox'];

if (shouldSkipTracingTest() || !supportedBrowsers.includes(browserName)) {
sentryTest.skip();
}

await page.route('**/path/to/script.js', (route: Route) =>
route.fulfill({ path: `${__dirname}/assets/script.js` }),
);

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

await page.goto(url);
await getFirstSentryEnvelopeRequest<Event>(page);

await page.locator('[data-test-id=annotated-button]').click();

const envelopes = await getMultipleSentryEnvelopeRequests<TransactionJSON>(page, 1);
expect(envelopes).toHaveLength(1);
const eventData = envelopes[0];

expect(eventData.spans).toHaveLength(1);

const interactionSpan = eventData.spans![0];
expect(interactionSpan.op).toBe('ui.interaction.click');
expect(interactionSpan.description).toBe('AnnotatedButton');
},
);
6 changes: 3 additions & 3 deletions packages/browser/src/integrations/breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import type {
} from '@sentry/types/build/types/breadcrumb';
import {
addInstrumentationHandler,
getElementIdentifier,
getEventDescription,
htmlTreeAsString,
logger,
parseUrl,
safeJoin,
Expand Down Expand Up @@ -153,8 +153,8 @@ function _domBreadcrumb(dom: BreadcrumbsOptions['dom']): (handlerData: HandlerDa
try {
const event = handlerData.event as Event | Node;
target = _isEvent(event)
? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })
: htmlTreeAsString(event, { keyAttrs, maxStringLength });
? getElementIdentifier(event.target, { keyAttrs, maxStringLength })
: getElementIdentifier(event, { keyAttrs, maxStringLength });
Comment on lines +156 to +157
Copy link
Member Author

Choose a reason for hiding this comment

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

Right now, getElementIdentifier isn't doing anything with the options passed to it, except passing it to htmlTreeAsString if there is no data-component annotation available. Would we want to make use of any of those options, like maxStringLength on the annotated component names as well?

} catch (e) {
target = '<unknown>';
}
Expand Down
4 changes: 2 additions & 2 deletions packages/replay/src/coreHandlers/handleDom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { record } from '@sentry-internal/rrweb';
import type { serializedElementNodeWithId, serializedNodeWithId } from '@sentry-internal/rrweb-snapshot';
import { NodeType } from '@sentry-internal/rrweb-snapshot';
import type { Breadcrumb } from '@sentry/types';
import { htmlTreeAsString } from '@sentry/utils';
import { getElementIdentifier } from '@sentry/utils';

import type { ReplayContainer } from '../types';
import { createBreadcrumb } from '../util/createBreadcrumb';
Expand Down Expand Up @@ -98,7 +98,7 @@ function getDomTarget(handlerData: DomHandlerData): { target: Node | null; messa
// Accessing event.target can throw (see getsentry/raven-js#838, #768)
try {
target = isClick ? getClickTargetNode(handlerData.event) : getTargetNode(handlerData.event);
message = htmlTreeAsString(target, { maxStringLength: 200 }) || '<unknown>';
message = getElementIdentifier(target, { maxStringLength: 200 }) || '<unknown>';
} catch (e) {
message = '<unknown>';
}
Expand Down
4 changes: 2 additions & 2 deletions packages/replay/src/coreHandlers/handleKeyboardEvent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Breadcrumb } from '@sentry/types';
import { htmlTreeAsString } from '@sentry/utils';
import { getElementIdentifier } from '@sentry/utils';

import type { ReplayContainer } from '../types';
import { createBreadcrumb } from '../util/createBreadcrumb';
Expand Down Expand Up @@ -45,7 +45,7 @@ export function getKeyboardBreadcrumb(event: KeyboardEvent): Breadcrumb | null {
return null;
}

const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '<unknown>';
const message = getElementIdentifier(target, { maxStringLength: 200 }) || '<unknown>';
const baseBreadcrumb = getBaseDomBreadcrumb(target as Node, message);

return createBreadcrumb({
Expand Down
8 changes: 4 additions & 4 deletions packages/tracing-internal/src/browser/metrics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import type { IdleTransaction, Transaction } from '@sentry/core';
import { getActiveTransaction } from '@sentry/core';
import type { Measurements } from '@sentry/types';
import { browserPerformanceTimeOrigin, htmlTreeAsString, logger } from '@sentry/utils';
import { browserPerformanceTimeOrigin, getElementIdentifier, logger } from '@sentry/utils';

import {
addClsInstrumentationHandler,
Expand Down Expand Up @@ -100,7 +100,7 @@ export function startTrackingInteractions(): void {
const duration = msToSec(entry.duration);

transaction.startChild({
description: htmlTreeAsString(entry.target),
description: getElementIdentifier(entry.target),
op: `ui.interaction.${entry.name}`,
origin: 'auto.ui.browser.metrics',
startTimestamp: startTime,
Expand Down Expand Up @@ -470,7 +470,7 @@ function _tagMetricInfo(transaction: Transaction): void {
// Capture Properties of the LCP element that contributes to the LCP.

if (_lcpEntry.element) {
transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));
transaction.setTag('lcp.element', getElementIdentifier(_lcpEntry.element));
}

if (_lcpEntry.id) {
Expand All @@ -489,7 +489,7 @@ function _tagMetricInfo(transaction: Transaction): void {
if (_clsEntry && _clsEntry.sources) {
__DEBUG_BUILD__ && logger.log('[Measurements] Adding CLS Data');
_clsEntry.sources.forEach((source, index) =>
transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),
transaction.setTag(`cls.source.${index + 1}`, getElementIdentifier(source.node)),
);
}
}
16 changes: 16 additions & 0 deletions packages/utils/src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,19 @@ export function getDomElement<E = any>(selector: string): E | null {
}
return null;
}

/**
* Given a child DOM element, returns the component name of the element.
* If the component name does not exist, this function will fallback to `htmlTreeAsString`
* e.g. [HTMLElement] => MyComponentName
*/
export function getElementIdentifier(
elem: unknown,
options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},
): string {
if (elem instanceof HTMLElement && elem.dataset) {
return elem.dataset['component'] || elem.dataset['element'] || htmlTreeAsString(elem, options);
}

return htmlTreeAsString(elem, options);
}
4 changes: 2 additions & 2 deletions packages/utils/src/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { WrappedFunction } from '@sentry/types';

import { htmlTreeAsString } from './browser';
import { getElementIdentifier } from './browser';
import { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';
import { logger } from './logger';
import { truncate } from './string';
Expand Down Expand Up @@ -150,7 +150,7 @@ export function convertToPlainObject<V>(value: V):
/** Creates a string representation of the target of an `Event` object */
function serializeEventTarget(target: unknown): string {
try {
return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
return isElement(target) ? getElementIdentifier(target) : Object.prototype.toString.call(target);
} catch (_oO) {
return '<unknown>';
}
Expand Down
3 changes: 3 additions & 0 deletions packages/utils/test/browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import { getDomElement, htmlTreeAsString } from '../src/browser';

beforeAll(() => {
const dom = new JSDOM();

// @ts-expect-error need to override global document
global.document = dom.window.document;
// @ts-expect-error need to add HTMLElement type or it will not be found
global.HTMLElement = new JSDOM().window.HTMLElement;
});

describe('htmlTreeAsString', () => {
Expand Down