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

✨ [RUMF-385] implement a declarative API to set the action names #412

Merged
merged 4 commits into from
Jun 2, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
20 changes: 20 additions & 0 deletions packages/rum/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,26 @@ datadogRum.init({
addUserAction (name: string, context: Context)
```

## Declarative API

### Click action naming

The RUM library is using various strategies to get a name for click actions, but if you want more
control, you can define a `data-dd-action-name` attribute on clickable elements (or any of their
parents) that will be used to name the action. Examples:

```html
<a class="btn btn-default" href="#" role="button" data-dd-action-name="Login button">Try it out!</a>
```

```html
<div class="alert alert-danger" role="alert" data-dd-action-name="Dismiss alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
Enter a valid email address
</div>
```

## TypeScript support

Types are compatible with TypeScript >= 3.0.
Expand Down
68 changes: 57 additions & 11 deletions packages/rum/src/getActionNameFromElement.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,51 @@
export function getActionNameFromElement(element: Element): string {
// Proceed to get the action name in two steps:
// * first, use strategies that are known to return good results. Those strategies will be used on
// * first, get the name programmatically, explicitely defined by the user.
// * then, use strategies that are known to return good results. Those strategies will be used on
Copy link
Contributor

Choose a reason for hiding this comment

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

what do you think of renaming "getters" to "strategies" in order to have a more consistent wording between comments and implementation?

Copy link
Member Author

Choose a reason for hiding this comment

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

Ok I'll rename this

// the element and a few parents, but it's likely that they won't succeed at all.
// * if no name is found this way, use strategies returning less accurate names as a fallback.
// Those are much likely to succeed.
return (
getActionNameFromElementForGetters(element, priorityGetters) ||
getActionNameFromElementForGetters(element, fallbackGetters) ||
getActionNameFromElementProgrammatically(element) ||
getActionNameFromElementForStrategies(element, priorityStrategies) ||
getActionNameFromElementForStrategies(element, fallbackStrategies) ||
''
)
}

type NameGetter = (element: Element | HTMLElement | HTMLInputElement | HTMLSelectElement) => string | undefined | null
/**
* Get the action name from the attribute 'data-dd-action-name' on the element or any of its parent.
*/
const PROGRAMMATIC_ATTRIBUTE = 'data-dd-action-name'
function getActionNameFromElementProgrammatically(targetElement: Element) {
let elementWithAttribute
// We don't use getActionNameFromElementForStrategies here, because we want to consider all parents,
// without limit. It is up to the user to declare a relevent naming strategy.
// If available, use element.closest() to match get the attribute from the element or any of its
// parent. Else fallback to a more traditional implementation.
if (supportsElementClosest()) {
elementWithAttribute = targetElement.closest(`[${PROGRAMMATIC_ATTRIBUTE}]`)
} else {
let element: Element | null = targetElement
while (element) {
if (element.hasAttribute(PROGRAMMATIC_ATTRIBUTE)) {
elementWithAttribute = element
break
}
element = element.parentElement
}
}

if (!elementWithAttribute) {
return
}
const name = elementWithAttribute.getAttribute(PROGRAMMATIC_ATTRIBUTE)!
return truncate(normalizeWhitespace(name.trim()))
}

const priorityGetters: NameGetter[] = [
type NameStrategy = (element: Element | HTMLElement | HTMLInputElement | HTMLSelectElement) => string | undefined | null

const priorityStrategies: NameStrategy[] = [
// associated LABEL text
(element) => {
// IE does not support element.labels, so we fallback to a CSS selector based on the element id
Expand Down Expand Up @@ -69,18 +101,18 @@ const priorityGetters: NameGetter[] = [
},
]

const fallbackGetters: NameGetter[] = [
const fallbackStrategies: NameStrategy[] = [
(element) => {
return getTextualContent(element)
},
]

/**
* Iterates over the target element and its parent, using the getters list to get an action name.
* Each getters are applied on each element, stopping as soon as a non-empty value is returned.
* Iterates over the target element and its parent, using the strategies list to get an action name.
* Each strategies are applied on each element, stopping as soon as a non-empty value is returned.
*/
const MAX_PARENTS_TO_CONSIDER = 10
function getActionNameFromElementForGetters(targetElement: Element, getters: NameGetter[]) {
function getActionNameFromElementForStrategies(targetElement: Element, strategies: NameStrategy[]) {
let element: Element | null = targetElement
let recursionCounter = 0
while (
Expand All @@ -90,8 +122,8 @@ function getActionNameFromElementForGetters(targetElement: Element, getters: Nam
element.nodeName !== 'HTML' &&
element.nodeName !== 'HEAD'
) {
for (const getter of getters) {
const name = getter(element)
for (const strategy of strategies) {
const name = strategy(element)
if (typeof name === 'string') {
const trimmedName = name.trim()
if (trimmedName) {
Expand Down Expand Up @@ -181,3 +213,17 @@ function supportsLabelProperty() {
}
return supportsLabelPropertyResult
}

/**
* Returns true if the browser supports the element.closest method. This should be the case
* everywhere except on Internet Explorer.
* Note: The result is computed lazily, because we don't want any DOM access when the SDK is
* evaluated.
*/
let supportsElementClosestResult: boolean | undefined
function supportsElementClosest() {
if (supportsElementClosestResult === undefined) {
supportsElementClosestResult = 'closest' in HTMLElement.prototype
}
return supportsElementClosestResult
}
43 changes: 43 additions & 0 deletions packages/rum/test/getActionNameFromElement.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,47 @@ describe('getActionNameFromElement', () => {
`)
).toBe('foo')
})

describe('programmatically declared action name', () => {
it('extracts the name from the data-dd-action-name attribute', () => {
expect(
getActionNameFromElement(element`
<div data-dd-action-name="foo">ignored</div>
`)
).toBe('foo')
})

it('considers any parent', () => {
const target = element`
<form>
<i><i><i><i><i><i><i><i><i><i><i><i>
<span target>ignored</span>
</i></i></i></i></i></i></i></i></i></i></i></i>
</form>
`
// Set the attribute on the <HTML> element
target.ownerDocument!.documentElement.setAttribute('data-dd-action-name', 'foo')
expect(getActionNameFromElement(target)).toBe('foo')
})

it('normalizes the value', () => {
expect(
getActionNameFromElement(element`
<div data-dd-action-name=" foo \t bar ">ignored</div>
`)
).toBe('foo bar')
})

it('fallback on an automatic strategy if the attribute is empty', () => {
expect(
getActionNameFromElement(element`
<div data-dd-action-name="ignored">
<div data-dd-action-name="">
<span target>foo</span>
</div>
</div>
`)
).toBe('foo')
})
})
})