1
0

utils.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 onboardingOpenButton = page.locator('strong:has-text("Choose a folder")')
  115. if (await onboardingOpenButton.isVisible()) {
  116. await onboardingOpenButton.click()
  117. } else {
  118. console.log("No onboarding button, loading file manually")
  119. let sidebar = page.locator('#left-sidebar')
  120. if (!/is-open/.test(await sidebar.getAttribute('class') || '')) {
  121. await page.click('#left-menu.button')
  122. await expect(sidebar).toHaveClass(/is-open/)
  123. }
  124. await page.click('#left-sidebar #repo-switch');
  125. await page.waitForSelector('#left-sidebar .dropdown-wrapper >> text="Add new graph"',
  126. { state: 'visible', timeout: 5000 })
  127. await page.click('text=Add new graph')
  128. expect(page.locator('#repo-name')).toHaveText(pathlib.basename(path))
  129. }
  130. setMockedOpenDirPath(page, ''); // reset it
  131. await page.waitForSelector(':has-text("Parsing files")', {
  132. state: 'hidden',
  133. timeout: 1000 * 60 * 5,
  134. })
  135. const title = await page.title()
  136. if (title === "Import data into Logseq" || title === "Add another repo") {
  137. await page.click('a.button >> text=Skip')
  138. }
  139. await page.waitForFunction('window.document.title === "Logseq"')
  140. await page.waitForTimeout(500)
  141. // If there is an error notification from a previous test graph being deleted,
  142. // close it first so it doesn't cover up the UI
  143. let n = await page.locator('.notification-close-button').count()
  144. if (n > 1) {
  145. await page.locator('button >> text="Clear all"').click()
  146. } else if (n == 1) {
  147. await page.locator('.notification-close-button').click()
  148. }
  149. await expect(page.locator('.notification-close-button').first()).not.toBeVisible({ timeout: 2000 })
  150. console.log('Graph loaded for ' + path)
  151. }
  152. export async function editNthBlock(page: Page, n) {
  153. await page.click(`.ls-block .block-content >> nth=${n}`)
  154. }
  155. export async function editFirstBlock(page: Page) {
  156. await editNthBlock(page, 0)
  157. }
  158. /**
  159. * Wait for a console message with a given prefix to appear, and return the full text of the message
  160. * Or reject after a timeout
  161. *
  162. * @param page
  163. * @param prefix - the prefix to look for
  164. * @param timeout - the timeout in ms
  165. * @returns the full text of the console message
  166. */
  167. export async function captureConsoleWithPrefix(page: Page, prefix: string, timeout: number = 3000): Promise<string> {
  168. return new Promise((resolve, reject) => {
  169. let console_handler = (msg: ConsoleMessage) => {
  170. let text = msg.text()
  171. if (text.startsWith(prefix)) {
  172. page.removeListener('console', console_handler)
  173. resolve(text.substring(prefix.length))
  174. }
  175. }
  176. page.on('console', console_handler)
  177. setTimeout(reject.bind("timeout"), timeout)
  178. })
  179. }
  180. export async function queryPermission(page: Page, permission: PermissionName): Promise<boolean> {
  181. // Check if WebAPI clipboard supported
  182. return await page.evaluate(async (eval_permission: PermissionName): Promise<boolean> => {
  183. if (typeof navigator.permissions == "undefined")
  184. return Promise.resolve(false);
  185. return navigator.permissions.query({
  186. name: eval_permission
  187. }).then((result: PermissionStatus): boolean => {
  188. return (result.state == "granted" || result.state == "prompt")
  189. })
  190. }, permission)
  191. }
  192. export async function doesClipboardItemExists(page: Page): Promise<boolean> {
  193. // Check if WebAPI clipboard supported
  194. return await page.evaluate((): boolean => {
  195. return typeof ClipboardItem !== "undefined"
  196. })
  197. }
  198. export async function getIsWebAPIClipboardSupported(page: Page): Promise<boolean> {
  199. // @ts-ignore "clipboard-write" is not included in TS's type definition for permissionName
  200. return await queryPermission(page, "clipboard-write") && await doesClipboardItemExists(page)
  201. }
  202. export async function navigateToStartOfBlock(page: Page, block: Block) {
  203. const selectionStart = await block.selectionStart()
  204. for (let i = 0; i < selectionStart; i++) {
  205. await page.keyboard.press('ArrowLeft')
  206. }
  207. }
  208. /**
  209. * Repeats a key press a certain number of times.
  210. * @param {Page} page - The Page object.
  211. * @param {string} key - The key to press.
  212. * @param {number} times - The number of times to press the key.
  213. * @return {Promise<void>} - Promise which resolves when the key press repetition is done.
  214. */
  215. export async function repeatKeyPress(page: Page, key: string, times: number): Promise<void> {
  216. for (let i = 0; i < times; i++) {
  217. await page.keyboard.press(key);
  218. }
  219. }
  220. /**
  221. * Moves the cursor a certain number of characters to the right (positive value) or left (negative value).
  222. * @param {Page} page - The Page object.
  223. * @param {number} shift - The number of characters to move the cursor. Positive moves to the right, negative to the left.
  224. * @return {Promise<void>} - Promise which resolves when the cursor has moved.
  225. */
  226. export async function moveCursor(page: Page, shift: number): Promise<void> {
  227. const direction = shift < 0 ? 'ArrowLeft' : 'ArrowRight';
  228. const absShift = Math.abs(shift);
  229. await repeatKeyPress(page, direction, absShift);
  230. }
  231. /**
  232. * Selects a certain length of text in a textarea to the right of the cursor.
  233. * @param {Page} page - The Page object.
  234. * @param {number} length - The number of characters to select.
  235. * @return {Promise<void>} - Promise which resolves when the text selection is done.
  236. */
  237. export async function selectCharacters(page: Page, length: number): Promise<void> {
  238. await page.keyboard.down('Shift');
  239. await repeatKeyPress(page, 'ArrowRight', length);
  240. await page.keyboard.up('Shift');
  241. }
  242. /**
  243. * Retrieves the selected text in a textarea.
  244. * @param {Page} page - The page object.
  245. * @return {Promise<string | null>} - Promise which resolves to the selected text or null.
  246. */
  247. export async function getSelection(page: Page): Promise<string | null> {
  248. const selection = await page.evaluate(() => {
  249. const textarea = document.querySelector('textarea')
  250. return textarea?.value.substring(textarea.selectionStart, textarea.selectionEnd) || null
  251. })
  252. return selection
  253. }
  254. /**
  255. * Retrieves the current cursor position in a textarea.
  256. * @param {Page} page - The page object.
  257. * @return {Promise<number | null>} - Promise which resolves to the cursor position or null.
  258. */
  259. export async function getCursorPos(page: Page): Promise<number | null> {
  260. const cursorPosition = await page.evaluate(() => {
  261. const textarea = document.querySelector('textarea');
  262. return textarea ? textarea.selectionStart : null;
  263. });
  264. return cursorPosition;
  265. }