utils.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import { Page, Locator } from 'playwright'
  2. import { expect, ConsoleMessage } from '@playwright/test'
  3. import * as pathlib from 'path'
  4. import { modKey } from './util/basic'
  5. import { Block } from './types'
  6. // TODO: The file should be a facade of utils in the /util folder
  7. // No more additional functions should be added to this file
  8. // Move the functions to the corresponding files in the /util folder
  9. // Criteria: If the same selector is shared in multiple functions, they should be in the same file
  10. export * from './util/basic'
  11. export * from './util/search-modal'
  12. export * from './util/page'
  13. /**
  14. * Locate the last block in the inner editor
  15. * @param page The Playwright Page object.
  16. * @returns The locator of the last block.
  17. */
  18. export async function lastBlock(page: Page): Promise<Locator> {
  19. // discard any popups
  20. await page.keyboard.press('Escape')
  21. // click last block
  22. if (await page.locator('text="Click here to edit..."').isVisible()) {
  23. await page.click('text="Click here to edit..."')
  24. } else {
  25. await page.click('.page-blocks-inner .ls-block >> nth=-1')
  26. }
  27. // wait for textarea
  28. await page.waitForSelector('textarea >> nth=0', { state: 'visible' })
  29. await page.waitForTimeout(100)
  30. return page.locator('textarea >> nth=0')
  31. }
  32. /**
  33. * Move the cursor to the beginning of the current editor
  34. * @param page The Playwright Page object.
  35. */
  36. export async function moveCursorToBeginning(page: Page): Promise<Locator> {
  37. await page.press('textarea >> nth=0', modKey + '+a') // select all
  38. await page.press('textarea >> nth=0', 'ArrowLeft')
  39. return page.locator('textarea >> nth=0')
  40. }
  41. /**
  42. * Move the cursor to the end of the current editor
  43. * @param page The Playwright Page object.
  44. */
  45. export async function moveCursorToEnd(page: Page): Promise<Locator> {
  46. await page.press('textarea >> nth=0', modKey + '+a') // select all
  47. await page.press('textarea >> nth=0', 'ArrowRight')
  48. return page.locator('textarea >> nth=0')
  49. }
  50. /**
  51. * Press Enter and create the next block.
  52. * @param page The Playwright Page object.
  53. */
  54. export async function enterNextBlock(page: Page): Promise<Locator> {
  55. // Move cursor to the end of the editor
  56. await page.press('textarea >> nth=0', modKey + '+a') // select all
  57. await page.press('textarea >> nth=0', 'ArrowRight')
  58. let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
  59. await page.press('textarea >> nth=0', 'Enter')
  60. await page.waitForTimeout(10)
  61. await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible' })
  62. return page.locator('textarea >> nth=0')
  63. }
  64. /**
  65. * Create and locate a new block at the end of the inner editor
  66. * @param page The Playwright Page object
  67. * @returns The locator of the last block
  68. */
  69. export async function newInnerBlock(page: Page): Promise<Locator> {
  70. await lastBlock(page)
  71. await page.press('textarea >> nth=0', 'Enter')
  72. return page.locator('textarea >> nth=0')
  73. }
  74. export async function escapeToCodeEditor(page: Page): Promise<void> {
  75. await page.press('.block-editor textarea', 'Escape')
  76. await page.waitForSelector('.CodeMirror pre', { state: 'visible' })
  77. await page.waitForTimeout(300)
  78. await page.click('.CodeMirror pre')
  79. await page.waitForTimeout(300)
  80. await page.waitForSelector('.CodeMirror textarea', { state: 'visible' })
  81. }
  82. export async function escapeToBlockEditor(page: Page): Promise<void> {
  83. await page.waitForTimeout(300)
  84. await page.click('.CodeMirror pre')
  85. await page.waitForTimeout(300)
  86. await page.press('.CodeMirror textarea', 'Escape')
  87. await page.waitForTimeout(300)
  88. }
  89. export async function setMockedOpenDirPath(
  90. page: Page,
  91. path?: string
  92. ): Promise<void> {
  93. // set next open directory
  94. await page.evaluate(
  95. ([path]) => {
  96. Object.assign(window, {
  97. __MOCKED_OPEN_DIR_PATH__: path,
  98. })
  99. },
  100. [path]
  101. )
  102. }
  103. export async function openLeftSidebar(page: Page): Promise<void> {
  104. let sidebar = page.locator('#left-sidebar')
  105. // Left sidebar is toggled by `is-open` class
  106. if (!/is-open/.test(await sidebar.getAttribute('class') || '')) {
  107. await page.click('#left-menu.button')
  108. await page.waitForTimeout(10)
  109. await expect(sidebar).toHaveClass(/is-open/)
  110. }
  111. }
  112. export async function loadLocalGraph(page: Page, path: string): Promise<void> {
  113. await setMockedOpenDirPath(page, path);
  114. const sidebar = page.locator('#left-sidebar')
  115. if (!/is-open/.test(await sidebar.getAttribute('class') || '')) {
  116. await page.click('#left-menu.button')
  117. await expect(sidebar).toHaveClass(/is-open/)
  118. }
  119. await page.click('#left-sidebar .cp__graphs-selector > a')
  120. await page.waitForTimeout(300)
  121. await page.waitForSelector('.cp__repos-quick-actions >> text="Add new graph"',
  122. { state: 'attached', timeout: 5000 })
  123. await page.click('text=Add new graph')
  124. await setMockedOpenDirPath(page, ''); // reset it
  125. await page.waitForSelector(':has-text("Parsing files")', {
  126. state: 'hidden',
  127. timeout: 1000 * 60 * 5,
  128. })
  129. const title = await page.title()
  130. if (title === "Import data into Logseq" || title === "Add another repo") {
  131. await page.click('a.button >> text=Skip')
  132. }
  133. await page.waitForFunction('window.document.title === "Logseq"')
  134. await page.waitForTimeout(500)
  135. // If there is an error notification from a previous test graph being deleted,
  136. // close it first so it doesn't cover up the UI
  137. let n = await page.locator('.notification-close-button').count()
  138. if (n > 1) {
  139. await page.locator('button >> text="Clear all"').click()
  140. } else if (n == 1) {
  141. await page.locator('.notification-close-button').click()
  142. }
  143. await expect(page.locator('.notification-close-button').first()).not.toBeVisible({ timeout: 2000 })
  144. console.log('Graph loaded for ' + path)
  145. }
  146. export async function editNthBlock(page: Page, n) {
  147. await page.click(`.ls-block .block-content >> nth=${n}`)
  148. }
  149. export async function editFirstBlock(page: Page) {
  150. await editNthBlock(page, 0)
  151. }
  152. /**
  153. * Wait for a console message with a given prefix to appear, and return the full text of the message
  154. * Or reject after a timeout
  155. *
  156. * @param page
  157. * @param prefix - the prefix to look for
  158. * @param timeout - the timeout in ms
  159. * @returns the full text of the console message
  160. */
  161. export async function captureConsoleWithPrefix(page: Page, prefix: string, timeout: number = 3000): Promise<string> {
  162. return new Promise((resolve, reject) => {
  163. let console_handler = (msg: ConsoleMessage) => {
  164. let text = msg.text()
  165. if (text.startsWith(prefix)) {
  166. page.removeListener('console', console_handler)
  167. resolve(text.substring(prefix.length))
  168. }
  169. }
  170. page.on('console', console_handler)
  171. setTimeout(reject.bind("timeout"), timeout)
  172. })
  173. }
  174. export async function queryPermission(page: Page, permission: PermissionName): Promise<boolean> {
  175. // Check if WebAPI clipboard supported
  176. return await page.evaluate(async (eval_permission: PermissionName): Promise<boolean> => {
  177. if (typeof navigator.permissions == "undefined")
  178. return Promise.resolve(false);
  179. return navigator.permissions.query({
  180. name: eval_permission
  181. }).then((result: PermissionStatus): boolean => {
  182. return (result.state == "granted" || result.state == "prompt")
  183. })
  184. }, permission)
  185. }
  186. export async function doesClipboardItemExists(page: Page): Promise<boolean> {
  187. // Check if WebAPI clipboard supported
  188. return await page.evaluate((): boolean => {
  189. return typeof ClipboardItem !== "undefined"
  190. })
  191. }
  192. export async function getIsWebAPIClipboardSupported(page: Page): Promise<boolean> {
  193. // @ts-ignore "clipboard-write" is not included in TS's type definition for permissionName
  194. return await queryPermission(page, "clipboard-write") && await doesClipboardItemExists(page)
  195. }
  196. export async function navigateToStartOfBlock(page: Page, block: Block) {
  197. const selectionStart = await block.selectionStart()
  198. for (let i = 0; i < selectionStart; i++) {
  199. await page.keyboard.press('ArrowLeft')
  200. }
  201. }
  202. /**
  203. * Repeats a key press a certain number of times.
  204. * @param {Page} page - The Page object.
  205. * @param {string} key - The key to press.
  206. * @param {number} times - The number of times to press the key.
  207. * @return {Promise<void>} - Promise which resolves when the key press repetition is done.
  208. */
  209. export async function repeatKeyPress(page: Page, key: string, times: number): Promise<void> {
  210. for (let i = 0; i < times; i++) {
  211. await page.keyboard.press(key);
  212. }
  213. }
  214. /**
  215. * Moves the cursor a certain number of characters to the right (positive value) or left (negative value).
  216. * @param {Page} page - The Page object.
  217. * @param {number} shift - The number of characters to move the cursor. Positive moves to the right, negative to the left.
  218. * @return {Promise<void>} - Promise which resolves when the cursor has moved.
  219. */
  220. export async function moveCursor(page: Page, shift: number): Promise<void> {
  221. const direction = shift < 0 ? 'ArrowLeft' : 'ArrowRight';
  222. const absShift = Math.abs(shift);
  223. await repeatKeyPress(page, direction, absShift);
  224. }
  225. /**
  226. * Selects a certain length of text in a textarea to the right of the cursor.
  227. * @param {Page} page - The Page object.
  228. * @param {number} length - The number of characters to select.
  229. * @return {Promise<void>} - Promise which resolves when the text selection is done.
  230. */
  231. export async function selectCharacters(page: Page, length: number): Promise<void> {
  232. await page.keyboard.down('Shift');
  233. await repeatKeyPress(page, 'ArrowRight', length);
  234. await page.keyboard.up('Shift');
  235. }
  236. /**
  237. * Retrieves the selected text in a textarea.
  238. * @param {Page} page - The page object.
  239. * @return {Promise<string | null>} - Promise which resolves to the selected text or null.
  240. */
  241. export async function getSelection(page: Page): Promise<string | null> {
  242. const selection = await page.evaluate(() => {
  243. const textarea = document.querySelector('textarea')
  244. return textarea?.value.substring(textarea.selectionStart, textarea.selectionEnd) || null
  245. })
  246. return selection
  247. }
  248. /**
  249. * Retrieves the current cursor position in a textarea.
  250. * @param {Page} page - The page object.
  251. * @return {Promise<number | null>} - Promise which resolves to the cursor position or null.
  252. */
  253. export async function getCursorPos(page: Page): Promise<number | null> {
  254. const cursorPosition = await page.evaluate(() => {
  255. const textarea = document.querySelector('textarea');
  256. return textarea ? textarea.selectionStart : null;
  257. });
  258. return cursorPosition;
  259. }
  260. /**
  261. * @param page
  262. * @param method
  263. * @param args
  264. */
  265. export async function callPageAPI(page, method, ...args) {
  266. return await page.evaluate(([method, args]) => {
  267. // @ts-ignore
  268. return window.logseq.api[method]?.(...args)
  269. }, [method, args])
  270. }