-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathShadowDomService.java
More file actions
411 lines (333 loc) · 17.3 KB
/
ShadowDomService.java
File metadata and controls
411 lines (333 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*
* Copyright 2024 Automate The Planet Ltd.
* Author: Miriam Kyoseva
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package solutions.bellatrix.web.components.shadowdom;
import lombok.experimental.UtilityClass;
import org.openqa.selenium.By;
import solutions.bellatrix.core.configuration.ConfigurationService;
import solutions.bellatrix.core.utilities.InstanceFactory;
import solutions.bellatrix.core.utilities.Ref;
import solutions.bellatrix.core.utilities.Wait;
import solutions.bellatrix.web.components.WebComponent;
import solutions.bellatrix.web.configuration.WebSettings;
import solutions.bellatrix.web.findstrategies.CssFindStrategy;
import solutions.bellatrix.web.findstrategies.FindStrategy;
import solutions.bellatrix.web.findstrategies.ShadowXPathFindStrategy;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.Callable;
@UtilityClass
public class ShadowDomService {
private static final String CHILD_COMBINATOR = " > ";
private static final String SHADOW_ROOT_TAG = "shadow-root";
public static String getShadowHtml(WebComponent shadowComponent, boolean isShadowRoot) {
return shadowComponent.getJavaScriptService()
.<String>genericExecute(String.format("return (%s)(arguments[0], arguments[1]);", getInnerHtmlScript),
shadowComponent.findElement(), isShadowRoot);
}
public static <TComponent extends WebComponent, TFindStrategy extends FindStrategy> TComponent createFromShadowRoot(Class<TComponent> componentClass, ShadowRoot parentComponent, TFindStrategy findStrategy) {
return createAllFromShadowRoot(componentClass, parentComponent, findStrategy).get(0);
}
public static <TComponent extends WebComponent, TFindStrategy extends FindStrategy> List<TComponent> createAllFromShadowRoot(Class<TComponent> componentClass, ShadowRoot parentComponent, TFindStrategy findStrategy) {
var locator = convertToCssOrXpath(findStrategy);
var foundLocators = getAbsoluteCss(parentComponent, locator);
List<TComponent> componentList = new ArrayList<>(foundLocators.length);
for (var i = 0; i < foundLocators.length; i++) {
Ref<String> currentCss = new Ref<>(foundLocators[i]);
var component = buildMissingShadowRootsAndCreate(componentClass, parentComponent, currentCss);
if (findStrategy.convert() instanceof By.ByXPath) {
component.setFindStrategy(new ShadowXPathFindStrategy(findStrategy.getValue(), currentCss.value));
} else {
component.setFindStrategy(new CssFindStrategy(currentCss.value));
}
componentList.add(component);
}
return componentList;
}
public static <TComponent extends WebComponent, TFindStrategy extends FindStrategy> TComponent createInShadowContext(Class<TComponent> componentClass, WebComponent parentComponent, TFindStrategy findStrategy) {
return createAllInShadowContext(componentClass, parentComponent, findStrategy).get(0);
}
public static <TComponent extends WebComponent, TFindStrategy extends FindStrategy> List<TComponent> createAllInShadowContext(Class<TComponent> componentClass, WebComponent parentComponent, TFindStrategy findStrategy) {
var locator = convertToCssOrXpath(findStrategy);
var parentLocator = retraceParentShadowRoots(parentComponent);
var outermostShadowRoot = getOutermostShadowRoot(parentComponent);
var foundLocators = getRelativeCss(outermostShadowRoot, locator, parentLocator);
List<TComponent> componentList = new ArrayList<>(foundLocators.length);
for (var i = 0; i < foundLocators.length; i++) {
Ref<String> currentCss = new Ref<>(foundLocators[i]);
var component = buildMissingShadowRootsAndCreate(componentClass, outermostShadowRoot, currentCss);
if (findStrategy.convert() instanceof By.ByXPath) {
component.setFindStrategy(new ShadowXPathFindStrategy(findStrategy.getValue(), currentCss.value));
} else {
component.setFindStrategy(new CssFindStrategy(currentCss.value));
}
componentList.add(component);
}
return componentList;
}
private static String[] getAbsoluteCss(ShadowRoot shadowRoot, String locator) {
Callable<String[]> js = () -> {
return shadowRoot.getJavaScriptService()
.<ArrayList<String>>genericExecute(String.format("return (%s)(arguments[0], arguments[1], arguments[2]);", javaScript),
shadowRoot.findElement(), locator, null).toArray(String[]::new);
};
return getCss(js, locator);
}
private static String[] getRelativeCss(ShadowRoot shadowRoot, String locator, String parentLocator) {
Callable<String[]> js = () -> {
return shadowRoot.getJavaScriptService()
.<ArrayList<String>>genericExecute(String.format("return (%s)(arguments[0], arguments[1], arguments[2]);", javaScript),
shadowRoot.findElement(), locator, parentLocator).toArray(String[]::new);
};
return getCss(js, locator);
}
private static String[] getCss(Callable<String[]> callable, String locator) {
if (Wait.retry(() -> {
String[] foundElements;
try {
foundElements = callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
if (foundElements == null || foundElements.length == 0) {
// continue
}
}, Duration.ofSeconds(ConfigurationService.get(WebSettings.class).getTimeoutSettings().getElementWaitTimeout()), Duration.ofSeconds(1), false)) {
try {
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
throw new IllegalArgumentException("No elements inside the shadow DOM were found with the locator: " + locator);
}
}
private static <TComponent extends WebComponent> TComponent buildMissingShadowRootsAndCreate(Class<TComponent> clazz, ShadowRoot parentComponent, Ref<String> fullCss) {
var component = InstanceFactory.create(clazz);
String[] fullCssArray = fullCss.value.split(CHILD_COMBINATOR + SHADOW_ROOT_TAG + CHILD_COMBINATOR);
ShadowRoot parent = parentComponent;
// we don't need the last String in the array when building the missing shadow root parents,
// as it is the local css relative to the innermost shadow root parent
for (var i = 0; i < fullCssArray.length - 1; i++) {
var nestedShadowRoot = InstanceFactory.create(ShadowRoot.class);
nestedShadowRoot.setFindStrategy(new CssFindStrategy(fullCssArray[i]));
nestedShadowRoot.setParentComponent(parent);
nestedShadowRoot.setParentWrappedElement(parent.getWrappedElement());
parent = nestedShadowRoot;
}
fullCss.value = fullCssArray[fullCssArray.length - 1];
component.setParentComponent(parent);
component.setParentWrappedElement(parent.getWrappedElement());
return component;
}
private static ShadowRoot getOutermostShadowRoot(WebComponent component) {
var parent = component.getParentComponent();
ShadowRoot outermostShadowRoot = null;
while (parent instanceof ShadowRoot) {
outermostShadowRoot = (ShadowRoot)parent;
parent = parent.getParentComponent();
}
return outermostShadowRoot;
}
private static int getNestedLevel(WebComponent component) {
var parent = component.getParentComponent();
var count = 0;
while (parent instanceof ShadowRoot) {
count++;
parent = parent.getParentComponent();
}
return count;
}
private static String retraceParentShadowRoots(WebComponent component) {
if (getNestedLevel(component) > 1 && component.inShadowContext()) {
var parent = component.getParentComponent();
Stack<String> findStrategies = new Stack<>();
findStrategies.push(component.getFindStrategy().getValue());
while (parent instanceof ShadowRoot && parent.inShadowContext()) {
findStrategies.push(CHILD_COMBINATOR + SHADOW_ROOT_TAG + CHILD_COMBINATOR);
findStrategies.push(parent.getFindStrategy().getValue());
parent = parent.getParentComponent();
}
StringBuilder finalCss = new StringBuilder();
while(!findStrategies.isEmpty()) {
finalCss.append(findStrategies.pop());
}
return finalCss.toString();
} else {
return component.getFindStrategy().getValue();
}
}
private static boolean checkIfCss(FindStrategy findStrategy) {
var strategyType = findStrategy.convert();
return !(strategyType instanceof By.ByLinkText) && !(strategyType instanceof By.ByPartialLinkText) && !(strategyType instanceof By.ByXPath);
}
private static String convertToCssOrXpath(FindStrategy findStrategy) {
var strategyType = findStrategy.convert();
var strategyValue = findStrategy.getValue();
if (strategyType instanceof By.ByCssSelector) {
return strategyValue;
}
if (findStrategy.convert() instanceof By.ByXPath) {
return strategyValue;
}
if (findStrategy.convert() instanceof By.ById) {
return String.format("[id='%s']", strategyValue);
}
if (strategyType instanceof By.ByName) {
return String.format("[name='%s']", strategyValue);
}
if (strategyType instanceof By.ByClassName) {
return String.format("[class='%s']", strategyValue);
}
if (strategyType instanceof By.ByLinkText) {
return String.format("//a[text()='%s']", strategyValue);
}
if (strategyType instanceof By.ByTagName) {
return strategyValue;
}
if (strategyType instanceof By.ByPartialLinkText) {
return String.format("//a[contains(text(), '%s')]", strategyValue);
}
return null;
}
private static final String javaScript = /* lang=js */ """
function (element, locator, relativeElementCss) {
const child_combinator = " > ";
const node = "/";
function clone(element, tag) {
let cloneElement;
if (element instanceof ShadowRoot && !tag) {
cloneElement = new DocumentFragment();
} else if (tag) {
cloneElement = document.createElement(tag);
}
else {
cloneElement = element.cloneNode();
if (element.firstChild && element.firstChild.nodeType === 3) {
cloneElement.appendChild(element.firstChild.cloneNode());
}
}
if (element.shadowRoot) {
cloneElement.appendChild(clone(element.shadowRoot, "shadow-root"));
}
if (element.children) {
for (const child of element.children) {
cloneElement.appendChild(clone(child, undefined));
}
}
return cloneElement;
}
function getAbsoluteXpath(element) {
function indexElement(el) {
let index = 1;
let previousSibling = el.previousElementSibling;
while (previousSibling) {
if (previousSibling.nodeName.toLowerCase() === el.nodeName.toLowerCase()) {
index++;
}
previousSibling = previousSibling.previousElementSibling;
}
if (el.tagName.toLowerCase() === "shadow-root") {
return node + el.tagName.toLowerCase();
} else {
return node + el.tagName.toLowerCase() + "[" + index + "]";
}
}
let xpath = [];
let currentElement = element;
while (currentElement) {
if (currentElement.tagName.toLowerCase() === 'html' || currentElement.tagName.toLowerCase() === 'body' || currentElement.tagName.startsWith() === '#' || currentElement.tagName.toLowerCase() === "temporary-div") {
break;
}
xpath.unshift(indexElement(currentElement));
currentElement = currentElement.parentElement;
}
return xpath.join("");
}
function getAbsoluteCss(xpath) {
let regex = new RegExp(node, 'g');
let cssSelector = xpath.replace(regex, child_combinator);
cssSelector = cssSelector.replace(/\\[(\\d+)\\]/g, ':nth-of-type($1)');
if (cssSelector.startsWith(child_combinator)) {
cssSelector = cssSelector.substring(child_combinator.length);
}
return cssSelector;
}
const temporaryDiv = document.createElement("temporary-div");
if (element.shadowRoot) {
temporaryDiv.appendChild(clone(element.shadowRoot, undefined));
} else {
temporaryDiv.appendChild(clone(element, "shadow-root"));
}
let startPoint = temporaryDiv;
if (relativeElementCss) {
startPoint = temporaryDiv.querySelector(relativeElementCss);
}
let elements;
if (locator.startsWith("/") || locator.startsWith("./") || locator.startsWith("(")) {
let result = document.evaluate(locator, startPoint, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
elements = [];
let node;
while ((node = result.iterateNext())) {
elements.push(node);
}
} else {
elements = Array.from(startPoint.querySelectorAll(locator));
}
let finalLocators = [];
elements.forEach((el) => {
finalLocators.push(getAbsoluteCss(getAbsoluteXpath(el)));
});
return finalLocators;
}""";
private static final String getInnerHtmlScript = """
function (element, isShadowRoot) {
const child_combinator = " > ";
const node = "/";
function clone(element, tag) {
let cloneElement;
if (element instanceof ShadowRoot && !tag) {
cloneElement = new DocumentFragment();
} else if (tag) {
cloneElement = document.createElement(tag);
}
else {
cloneElement = element.cloneNode();
if (element.firstChild && element.firstChild.nodeType === 3) {
cloneElement.appendChild(element.firstChild.cloneNode());
}
}
if (element.shadowRoot) {
cloneElement.appendChild(clone(element.shadowRoot, "shadow-root"));
}
if (element.children) {
for (const child of element.children) {
cloneElement.appendChild(clone(child, undefined));
}
}
return cloneElement;
}
let temporaryDiv = document.createElement("temporary-div");
if (element.shadowRoot) {
temporaryDiv.appendChild(clone(element.shadowRoot, undefined));
} else if (isShadowRoot) {
temporaryDiv.appendChild(clone(element, "shadow-root"));
} else {
temporaryDiv.appendChild(clone(element, "redundant-el"));
temporaryDiv = temporaryDiv.querySelector("redundant-el");
}
return temporaryDiv.innerHTML;
}
""";
}