@cypress/unique-selector 0.0.0-dev.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +285 -0
- package/package.json +58 -0
package/README.md
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
# unique-selector
|
|
2
|
+
|
|
3
|
+
Given a DOM node, return a unique CSS selector matching only that element.
|
|
4
|
+
|
|
5
|
+
Selector uniqueness is determined based on the given element's root node. Elements rendered within Shadow DOM will derive a selector unique within the associated ShadowRoot context. Otherwise, a selector unique within an element's owning document will be derived.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @cypress/unique-selector
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## API
|
|
16
|
+
|
|
17
|
+
### `unique(element, options)`
|
|
18
|
+
|
|
19
|
+
Generates a unique CSS selector for the given DOM element.
|
|
20
|
+
|
|
21
|
+
#### Parameters
|
|
22
|
+
|
|
23
|
+
- **`element`** (Element) - The DOM element for which to generate a unique selector
|
|
24
|
+
- **`options`** (Object, optional) - Configuration options for selector generation
|
|
25
|
+
|
|
26
|
+
#### Options
|
|
27
|
+
|
|
28
|
+
- **`selectorTypes`** (String[], optional) - Array of selector types to use in order of preference. Default: `['id', 'name', 'class', 'tag', 'nth-child']`
|
|
29
|
+
|
|
30
|
+
Available selector types:
|
|
31
|
+
- `'id'` - Uses element's ID attribute (e.g., `#myId`)
|
|
32
|
+
- `'name'` - Uses element's name attribute (e.g., `[name="myName"]`)
|
|
33
|
+
- `'class'` - Uses element's class attributes (e.g., `.myClass`)
|
|
34
|
+
- `'tag'` - Uses element's tag name (e.g., `div`, `span`)
|
|
35
|
+
- `'nth-child'` - Uses nth-child position (e.g., `:nth-child(1)`)
|
|
36
|
+
- `'attributes'` - Uses all attributes except those in `attributesToIgnore`
|
|
37
|
+
- `'data-*'` - Uses specific data attributes (e.g., `data-foo`, `data-test-id`)
|
|
38
|
+
- `'attribute:*'` - Uses specific attributes (e.g., `attribute:role`, `attribute:aria-label`)
|
|
39
|
+
|
|
40
|
+
- **`attributesToIgnore`** (String[], optional) - Array of attribute names to ignore when generating selectors. Default: `['id', 'class', 'length']`
|
|
41
|
+
|
|
42
|
+
- **`filter`** (Function, optional) - A filter function to conditionally reject various traits when building selectors.
|
|
43
|
+
|
|
44
|
+
```javascript
|
|
45
|
+
function filter(type, key, value) {
|
|
46
|
+
// type: 'attribute', 'class', 'tag', 'nth-child'
|
|
47
|
+
// key: attribute name (for attributes), class name (for classes), etc.
|
|
48
|
+
// value: attribute value, class name, tag name, nth-child position
|
|
49
|
+
|
|
50
|
+
// Return true to allow this trait, false to reject it
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
- **`selectorCache`** (Map<Element, String>, optional) - Cache to improve performance of repeated selector generation. The caller is responsible for cache invalidation.
|
|
56
|
+
|
|
57
|
+
- **`isUniqueCache`** (Map<String, Boolean>, optional) - Cache to improve performance of repeated uniqueness checks. The caller is responsible for cache invalidation.
|
|
58
|
+
|
|
59
|
+
- **`requiredAttributes`** (Object, optional) - Specifies attributes that must appear in the generated selector regardless of whether they are needed for uniqueness. When provided, matching attribute selectors are woven into every element's segment of the `>` chain, and ancestors above the unique chain are prepended using descendant combinators.
|
|
60
|
+
|
|
61
|
+
This option takes precedence over `selectorTypes` and `filter` for the attributes it names — if an element has a required attribute, its `[attr="value"]` selector will appear in the output even if `filter` would reject that attribute for uniqueness purposes, and even if the attribute is not listed in `selectorTypes`.
|
|
62
|
+
|
|
63
|
+
The `requiredAttributes` object has the following shape:
|
|
64
|
+
|
|
65
|
+
- **`attributeNames`** (String[]) - The attribute names to inject into the selector (e.g., `['data-component', 'data-cy']`). Exact attribute names only — not patterns or regexes. Names are used as-provided in the generated selector with no internal normalization, so the casing you supply is the casing that appears in the output. When an attribute in `attributeNames` is already present in the base selector (from `selectorTypes`), dedup detection is case-insensitive, so duplicate injection is correctly suppressed regardless of case differences.
|
|
66
|
+
- **`filter`** (Function, optional) - A filter function with the same signature as the top-level `filter` option, applied independently to control which attribute _values_ are allowed to be injected. Return `false` to skip injection for a given element. This filter is separate from the top-level `filter` and serves a different purpose: the top-level `filter` controls which traits are eligible for building a _unique_ selector, while `requiredAttributes.filter` controls which attribute values are eligible for _injection_. The `key` argument passed to this function will match the casing of the name as provided in `attributeNames`.
|
|
67
|
+
- **`elementCache`** (Map<Element, (string|null)[]>, optional) - Cache for per-element required attribute selectors. Each cached entry is an array of individual selector strings parallel to `attributeNames` (null for attributes not present or filtered out). The caller is responsible for cache invalidation.
|
|
68
|
+
|
|
69
|
+
```javascript
|
|
70
|
+
unique(element, {
|
|
71
|
+
requiredAttributes: {
|
|
72
|
+
attributeNames: ['data-component', 'data-cy'],
|
|
73
|
+
filter: (type, key, value) => {
|
|
74
|
+
// Exclude auto-generated component names from injection
|
|
75
|
+
if (type === 'attribute' && key === 'data-component') {
|
|
76
|
+
return !value.startsWith('jss-');
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
},
|
|
80
|
+
elementCache: new Map(),
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
#### Returns
|
|
86
|
+
|
|
87
|
+
- **String** - A unique CSS selector for the element, or `null` if no unique selector can be generated
|
|
88
|
+
|
|
89
|
+
## Usage Examples
|
|
90
|
+
|
|
91
|
+
### Basic Usage
|
|
92
|
+
|
|
93
|
+
```javascript
|
|
94
|
+
import unique from '@cypress/unique-selector';
|
|
95
|
+
|
|
96
|
+
// Get a unique selector for an element
|
|
97
|
+
const element = document.querySelector('.my-button');
|
|
98
|
+
const selector = unique(element);
|
|
99
|
+
// Returns: '#my-button' or '.my-button' or 'button' etc.
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Custom Selector Types
|
|
103
|
+
|
|
104
|
+
```javascript
|
|
105
|
+
// Use only ID and class selectors
|
|
106
|
+
const selector = unique(element, {
|
|
107
|
+
selectorTypes: ['id', 'class']
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// Use only data attributes
|
|
111
|
+
const selector = unique(element, {
|
|
112
|
+
selectorTypes: ['data-test-id', 'data-cy']
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
// Use specific attributes
|
|
116
|
+
const selector = unique(element, {
|
|
117
|
+
selectorTypes: ['attribute:role', 'attribute:aria-label']
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Filtering Selectors
|
|
122
|
+
|
|
123
|
+
```javascript
|
|
124
|
+
// Filter out certain IDs
|
|
125
|
+
const selector = unique(element, {
|
|
126
|
+
filter: (type, key, value) => {
|
|
127
|
+
if (type === 'attribute' && key === 'id') {
|
|
128
|
+
// Only allow IDs that contain 'test'
|
|
129
|
+
return value.includes('test');
|
|
130
|
+
}
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// Filter out certain classes
|
|
136
|
+
const selector = unique(element, {
|
|
137
|
+
filter: (type, key, value) => {
|
|
138
|
+
if (type === 'class') {
|
|
139
|
+
// Only allow classes that start with 'btn-'
|
|
140
|
+
return value.startsWith('btn-');
|
|
141
|
+
}
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Required Attributes
|
|
148
|
+
|
|
149
|
+
Use `requiredAttributes` when you want specific attributes to always appear in the generated selector, regardless of whether they contribute to uniqueness. This is useful when your application uses semantic component attributes (e.g., `data-component`, `data-cy`) that you want reflected in every selector for readability or stability.
|
|
150
|
+
|
|
151
|
+
```javascript
|
|
152
|
+
// Always include data-component in the selector, even when an ID alone would be unique
|
|
153
|
+
const selector = unique(element, {
|
|
154
|
+
requiredAttributes: {
|
|
155
|
+
attributeNames: ['data-component']
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
// '#submit-button' becomes '#submit-button[data-component="PrimaryButton"]'
|
|
159
|
+
// Ancestors with data-component are prepended with descendant combinators:
|
|
160
|
+
// '[data-component="Form"] #submit-button[data-component="PrimaryButton"]'
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Required attributes take precedence over `selectorTypes` and `filter`. If an element has a required attribute, it will be injected into the selector even if:
|
|
164
|
+
- The attribute is not listed in `selectorTypes`
|
|
165
|
+
- The top-level `filter` would reject that attribute for uniqueness purposes
|
|
166
|
+
|
|
167
|
+
```javascript
|
|
168
|
+
// The top-level filter rejects data-component for uniqueness building,
|
|
169
|
+
// but requiredAttributes.filter allows it to still be injected.
|
|
170
|
+
const selector = unique(element, {
|
|
171
|
+
filter: (type, key) => key !== 'data-component',
|
|
172
|
+
requiredAttributes: {
|
|
173
|
+
attributeNames: ['data-component'],
|
|
174
|
+
// No requiredAttributes.filter — all values are injected
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
// data-component still appears in the output
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Use `requiredAttributes.filter` independently to control which attribute _values_ get injected, without affecting how uniqueness is determined:
|
|
181
|
+
|
|
182
|
+
```javascript
|
|
183
|
+
// Inject data-component only when the value doesn't look auto-generated
|
|
184
|
+
const selector = unique(element, {
|
|
185
|
+
requiredAttributes: {
|
|
186
|
+
attributeNames: ['data-component'],
|
|
187
|
+
filter: (type, key, value) => {
|
|
188
|
+
if (type === 'attribute' && key === 'data-component') {
|
|
189
|
+
return !value.startsWith('jss-');
|
|
190
|
+
}
|
|
191
|
+
return true;
|
|
192
|
+
},
|
|
193
|
+
elementCache: new Map(), // reuse across calls for performance
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
When multiple `attributeNames` are specified, each is matched independently on every element:
|
|
199
|
+
|
|
200
|
+
```javascript
|
|
201
|
+
const selector = unique(element, {
|
|
202
|
+
requiredAttributes: {
|
|
203
|
+
attributeNames: ['data-cy', 'data-region']
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
// '[data-region="main"] [data-cy="dashboard"] .widget[data-cy="widget-a"]'
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### Performance Optimization with Caching
|
|
210
|
+
|
|
211
|
+
```javascript
|
|
212
|
+
const selectorCache = new Map();
|
|
213
|
+
const isUniqueCache = new Map();
|
|
214
|
+
|
|
215
|
+
const selector = unique(element, {
|
|
216
|
+
selectorCache,
|
|
217
|
+
isUniqueCache
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
// Reuse the same caches for multiple calls
|
|
221
|
+
const selector2 = unique(anotherElement, {
|
|
222
|
+
selectorCache,
|
|
223
|
+
isUniqueCache
|
|
224
|
+
});
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
### Shadow DOM Support
|
|
228
|
+
|
|
229
|
+
```javascript
|
|
230
|
+
// Works with Shadow DOM elements
|
|
231
|
+
const shadowHost = document.querySelector('#shadow-host');
|
|
232
|
+
const shadowRoot = shadowHost.attachShadow({ mode: 'open' });
|
|
233
|
+
const shadowElement = shadowRoot.querySelector('.shadow-button');
|
|
234
|
+
|
|
235
|
+
const selector = unique(shadowElement);
|
|
236
|
+
// Returns a selector unique within the shadow root context
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
## Selector Generation Strategy
|
|
240
|
+
|
|
241
|
+
The library follows this strategy to generate unique selectors:
|
|
242
|
+
|
|
243
|
+
1. **Element-level uniqueness**: First tries to find a selector that uniquely identifies the element within its parent
|
|
244
|
+
2. **Parent traversal**: If element-level uniqueness fails, traverses up the DOM tree, building a path of selectors
|
|
245
|
+
3. **Selector type precedence**: Uses the `selectorTypes` array to determine which selector types to try first
|
|
246
|
+
4. **Combination fallback**: For classes and attributes, tries combinations of multiple selectors if single selectors aren't unique
|
|
247
|
+
5. **Nth-child fallback**: Uses nth-child positioning as a last resort
|
|
248
|
+
6. **Required attribute injection**: After the unique `>` chain is determined, any `requiredAttributes` are woven into each element's segment of the chain. Ancestors above the chain that carry a required attribute are prepended as descendant combinators. Required attributes are injected even when they are not needed for uniqueness and even when the top-level `filter` would exclude them from consideration.
|
|
249
|
+
|
|
250
|
+
## Examples of Generated Selectors
|
|
251
|
+
|
|
252
|
+
```html
|
|
253
|
+
<!-- Element with ID -->
|
|
254
|
+
<div id="header">Header</div>
|
|
255
|
+
<!-- Selector: #header -->
|
|
256
|
+
|
|
257
|
+
<!-- Element with unique class -->
|
|
258
|
+
<button class="submit-btn">Submit</button>
|
|
259
|
+
<!-- Selector: .submit-btn -->
|
|
260
|
+
|
|
261
|
+
<!-- Element with multiple classes -->
|
|
262
|
+
<div class="card primary large">Card</div>
|
|
263
|
+
<!-- Selector: .card.primary.large -->
|
|
264
|
+
|
|
265
|
+
<!-- Element with data attributes -->
|
|
266
|
+
<div data-test-id="user-profile">Profile</div>
|
|
267
|
+
<!-- Selector: [data-test-id="user-profile"] -->
|
|
268
|
+
|
|
269
|
+
<!-- Element with custom attributes -->
|
|
270
|
+
<button role="button" aria-label="Close">×</button>
|
|
271
|
+
<!-- Selector: [role="button"] or [aria-label="Close"] -->
|
|
272
|
+
|
|
273
|
+
<!-- Element requiring nth-child -->
|
|
274
|
+
<div class="item">Item 1</div>
|
|
275
|
+
<div class="item">Item 2</div>
|
|
276
|
+
<!-- Selector: :nth-child(1) or :nth-child(2) -->
|
|
277
|
+
|
|
278
|
+
<!-- Complex nested element -->
|
|
279
|
+
<div class="container">
|
|
280
|
+
<div class="wrapper">
|
|
281
|
+
<span class="text">Hello</span>
|
|
282
|
+
</div>
|
|
283
|
+
</div>
|
|
284
|
+
<!-- Selector: .container > .wrapper > .text -->
|
|
285
|
+
```
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@cypress/unique-selector",
|
|
3
|
+
"version": "0.0.0-dev.50",
|
|
4
|
+
"description": "Given a DOM node, return a unique CSS selector matching only that element",
|
|
5
|
+
"main": "./lib/index.js",
|
|
6
|
+
"jsnext:main": "./src/index.js",
|
|
7
|
+
"directories": {
|
|
8
|
+
"test": "test"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "npm run compile",
|
|
12
|
+
"test": "npm run compile && mocha --ignore-leaks",
|
|
13
|
+
"compile": "babel -d lib/ src/",
|
|
14
|
+
"prepublishOnly": "npm run compile",
|
|
15
|
+
"watch": "npm-scripts-watcher"
|
|
16
|
+
},
|
|
17
|
+
"watch": {
|
|
18
|
+
"src/**/*.js": [
|
|
19
|
+
"compile"
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/cypress-io/unique-selector.git"
|
|
25
|
+
},
|
|
26
|
+
"keywords": [
|
|
27
|
+
"dom",
|
|
28
|
+
"html",
|
|
29
|
+
"css",
|
|
30
|
+
"selector",
|
|
31
|
+
"event"
|
|
32
|
+
],
|
|
33
|
+
"author": "Cypress",
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"babel-cli": "^6.26.0",
|
|
37
|
+
"babel-core": "^6.26.3",
|
|
38
|
+
"babel-preset-latest": "^6.24.1",
|
|
39
|
+
"babel-register": "^6.26.0",
|
|
40
|
+
"chai": "^4.3.4",
|
|
41
|
+
"component": "~1.1.0",
|
|
42
|
+
"eslint": "^8.57.1",
|
|
43
|
+
"eslint-config-airbnb": "^19.0.0",
|
|
44
|
+
"eslint-plugin-react": "^7.37.5",
|
|
45
|
+
"jquery": "^3.6.0",
|
|
46
|
+
"jsdom": "^27.4.0",
|
|
47
|
+
"mocha": "~9.1.3",
|
|
48
|
+
"mocha-jsdom": "^2.0.0",
|
|
49
|
+
"mocha-phantomjs": "~4.1.0",
|
|
50
|
+
"npm-scripts-watcher": "^1.0.2"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"css.escape": "^1.5.1"
|
|
54
|
+
},
|
|
55
|
+
"files": [
|
|
56
|
+
"lib"
|
|
57
|
+
]
|
|
58
|
+
}
|