Selection.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const Helper = require("@codeceptjs/helper");
  2. const getPage = (h) => {
  3. return (h.Puppeteer ?? h.Playwright).page;
  4. };
  5. class Selection extends Helper {
  6. async dblClickOnWord(text, parent = "*") {
  7. const page = getPage(this.helpers);
  8. const { mouse } = page;
  9. const xpath = [locate(parent).toXPath(), `//text()[contains(., '${text}')]`, "[last()]"].join("");
  10. const point = await page.evaluate(
  11. ({ xpath, text }) => {
  12. const textEl = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();
  13. const pos = textEl.wholeText.search(text);
  14. const range = new Range();
  15. range.setStart(textEl, pos);
  16. range.setEnd(textEl, pos + 1);
  17. const bbox = range.getBoundingClientRect();
  18. return {
  19. x: (bbox.left + bbox.right) / 2,
  20. y: (bbox.top + bbox.bottom) / 2,
  21. };
  22. },
  23. { xpath, text },
  24. );
  25. return mouse.click(point.x, point.y, { button: "left", clickCount: 2, delay: 50 });
  26. }
  27. async dblClickOnElement(elementLocator) {
  28. const page = getPage(this.helpers);
  29. const { mouse } = page;
  30. const elsXpath = locate(elementLocator).toXPath();
  31. const point = await page.evaluate((elsXpath) => {
  32. const el = document.evaluate(elsXpath, document, null, XPathResult.ANY_TYPE, null).iterateNext();
  33. const bbox = el.getBoundingClientRect();
  34. return {
  35. x: (bbox.left + bbox.right) / 2,
  36. y: (bbox.top + bbox.bottom) / 2,
  37. };
  38. }, elsXpath);
  39. return mouse.click(point.x, point.y, { button: "left", clickCount: 2, delay: 50 });
  40. }
  41. async setSelection(startLocator, startOffset, endLocator, endOffset) {
  42. const page = getPage(this.helpers);
  43. const startContainerXPath = locate(startLocator).toXPath();
  44. const endContainerXPath = locate(endLocator).toXPath();
  45. await page.evaluate(
  46. ({ startContainerXPath, startOffset, endContainerXPath, endOffset }) => {
  47. const startContainer = document
  48. .evaluate(startContainerXPath, document, null, XPathResult.ANY_TYPE, null)
  49. .iterateNext();
  50. const endContainer = document
  51. .evaluate(endContainerXPath, document, null, XPathResult.ANY_TYPE, null)
  52. .iterateNext();
  53. const range = new Range();
  54. range.setStart(startContainer, startOffset);
  55. range.setEnd(endContainer, endOffset);
  56. const selection = window.getSelection();
  57. selection.removeAllRanges();
  58. selection.addRange(range);
  59. const evt = new MouseEvent("mouseup");
  60. evt.initMouseEvent("mouseup", true, true);
  61. endContainer.dispatchEvent(evt);
  62. },
  63. { startContainerXPath, startOffset, endContainerXPath, endOffset },
  64. );
  65. }
  66. }
  67. module.exports = Selection;