utils.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. // TODO: The file should be a facade of utils in the /util folder
  6. // No more additional functions should be added to this file
  7. // Move the functions to the corresponding files in the /util folder
  8. // Criteria: If the same selector is shared in multiple functions, they should be in the same file
  9. export * from './util/basic'
  10. export * from './util/search-modal'
  11. export * from './util/page'
  12. /**
  13. * Locate the last block in the inner editor
  14. * @param page The Playwright Page object.
  15. * @returns The locator of the last block.
  16. */
  17. export async function lastBlock(page: Page): Promise<Locator> {
  18. // discard any popups
  19. await page.keyboard.press('Escape')
  20. // click last block
  21. if (await page.locator('text="Click here to edit..."').isVisible()) {
  22. await page.click('text="Click here to edit..."')
  23. } else {
  24. await page.click('.page-blocks-inner .ls-block >> nth=-1')
  25. }
  26. // wait for textarea
  27. await page.waitForSelector('textarea >> nth=0', { state: 'visible' })
  28. await page.waitForTimeout(100)
  29. return page.locator('textarea >> nth=0')
  30. }
  31. /**
  32. * Move the cursor to the beginning of the current editor
  33. * @param page The Playwright Page object.
  34. */
  35. export async function moveCursorToBeginning(page: Page): Promise<Locator> {
  36. await page.press('textarea >> nth=0', modKey + '+a') // select all
  37. await page.press('textarea >> nth=0', 'ArrowLeft')
  38. return page.locator('textarea >> nth=0')
  39. }
  40. /**
  41. * Move the cursor to the end of the current editor
  42. * @param page The Playwright Page object.
  43. */
  44. export async function moveCursorToEnd(page: Page): Promise<Locator> {
  45. await page.press('textarea >> nth=0', modKey + '+a') // select all
  46. await page.press('textarea >> nth=0', 'ArrowRight')
  47. return page.locator('textarea >> nth=0')
  48. }
  49. /**
  50. * Press Enter and create the next block.
  51. * @param page The Playwright Page object.
  52. */
  53. export async function enterNextBlock(page: Page): Promise<Locator> {
  54. // Move cursor to the end of the editor
  55. await page.press('textarea >> nth=0', modKey + '+a') // select all
  56. await page.press('textarea >> nth=0', 'ArrowRight')
  57. let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
  58. await page.press('textarea >> nth=0', 'Enter')
  59. await page.waitForTimeout(10)
  60. await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible' })
  61. return page.locator('textarea >> nth=0')
  62. }
  63. /**
  64. * Create and locate a new block at the end of the inner editor
  65. * @param page The Playwright Page object
  66. * @returns The locator of the last block
  67. */
  68. export async function newInnerBlock(page: Page): Promise<Locator> {
  69. await lastBlock(page)
  70. await page.press('textarea >> nth=0', 'Enter')
  71. return page.locator('textarea >> nth=0')
  72. }
  73. export async function escapeToCodeEditor(page: Page): Promise<void> {
  74. await page.press('.block-editor textarea', 'Escape')
  75. await page.waitForSelector('.CodeMirror pre', { state: 'visible' })
  76. await page.waitForTimeout(300)
  77. await page.click('.CodeMirror pre')
  78. await page.waitForTimeout(300)
  79. await page.waitForSelector('.CodeMirror textarea', { state: 'visible' })
  80. }
  81. export async function escapeToBlockEditor(page: Page): Promise<void> {
  82. await page.waitForTimeout(300)
  83. await page.click('.CodeMirror pre')
  84. await page.waitForTimeout(300)
  85. await page.press('.CodeMirror textarea', 'Escape')
  86. await page.waitForTimeout(300)
  87. }
  88. export async function setMockedOpenDirPath(
  89. page: Page,
  90. path?: string
  91. ): Promise<void> {
  92. // set next open directory
  93. await page.evaluate(
  94. ([path]) => {
  95. Object.assign(window, {
  96. __MOCKED_OPEN_DIR_PATH__: path,
  97. })
  98. },
  99. [path]
  100. )
  101. }
  102. export async function openLeftSidebar(page: Page): Promise<void> {
  103. let sidebar = page.locator('#left-sidebar')
  104. // Left sidebar is toggled by `is-open` class
  105. if (!/is-open/.test(await sidebar.getAttribute('class') || '')) {
  106. await page.click('#left-menu.button')
  107. await page.waitForTimeout(10)
  108. await expect(sidebar).toHaveClass(/is-open/)
  109. }
  110. }
  111. export async function loadLocalGraph(page: Page, path: string): Promise<void> {
  112. await setMockedOpenDirPath(page, path);
  113. const onboardingOpenButton = page.locator('strong:has-text("Choose a folder")')
  114. if (await onboardingOpenButton.isVisible()) {
  115. await onboardingOpenButton.click()
  116. } else {
  117. console.log("No onboarding button, loading file manually")
  118. let sidebar = page.locator('#left-sidebar')
  119. if (!/is-open/.test(await sidebar.getAttribute('class') || '')) {
  120. await page.click('#left-menu.button')
  121. await expect(sidebar).toHaveClass(/is-open/)
  122. }
  123. await page.click('#left-sidebar #repo-switch');
  124. await page.waitForSelector('#left-sidebar .dropdown-wrapper >> text="Add new graph"',
  125. { state: 'visible', timeout: 5000 })
  126. await page.click('text=Add new graph')
  127. expect(page.locator('#repo-name')).toHaveText(pathlib.basename(path))
  128. }
  129. setMockedOpenDirPath(page, ''); // reset it
  130. await page.waitForSelector(':has-text("Parsing files")', {
  131. state: 'hidden',
  132. timeout: 1000 * 60 * 5,
  133. })
  134. const title = await page.title()
  135. if (title === "Import data into Logseq" || title === "Add another repo") {
  136. await page.click('a.button >> text=Skip')
  137. }
  138. await page.waitForFunction('window.document.title === "Logseq"')
  139. await page.waitForTimeout(500)
  140. // If there is an error notification from a previous test graph being deleted,
  141. // close it first so it doesn't cover up the UI
  142. let n = await page.locator('.notification-close-button').count()
  143. if (n > 1) {
  144. await page.locator('button >> text="Clear all"').click()
  145. } else if (n == 1) {
  146. await page.locator('.notification-close-button').click()
  147. }
  148. await expect(page.locator('.notification-close-button').first()).not.toBeVisible({ timeout: 2000 })
  149. console.log('Graph loaded for ' + path)
  150. }
  151. export async function editNthBlock(page: Page, n) {
  152. await page.click(`.ls-block .block-content >> nth=${n}`)
  153. }
  154. export async function editFirstBlock(page: Page) {
  155. await editNthBlock(page, 0)
  156. }
  157. /**
  158. * Wait for a console message with a given prefix to appear, and return the full text of the message
  159. * Or reject after a timeout
  160. *
  161. * @param page
  162. * @param prefix - the prefix to look for
  163. * @param timeout - the timeout in ms
  164. * @returns the full text of the console message
  165. */
  166. export async function captureConsoleWithPrefix(page: Page, prefix: string, timeout: number = 3000): Promise<string> {
  167. return new Promise((resolve, reject) => {
  168. let console_handler = (msg: ConsoleMessage) => {
  169. let text = msg.text()
  170. if (text.startsWith(prefix)) {
  171. page.removeListener('console', console_handler)
  172. resolve(text.substring(prefix.length))
  173. }
  174. }
  175. page.on('console', console_handler)
  176. setTimeout(reject.bind("timeout"), timeout)
  177. })
  178. }
  179. export async function queryPermission(page: Page, permission: PermissionName): Promise<boolean> {
  180. // Check if WebAPI clipboard supported
  181. return await page.evaluate(async (eval_permission: PermissionName): Promise<boolean> => {
  182. if (typeof navigator.permissions == "undefined")
  183. return Promise.resolve(false);
  184. return navigator.permissions.query({
  185. name: eval_permission
  186. }).then((result: PermissionStatus): boolean => {
  187. return (result.state == "granted" || result.state == "prompt")
  188. })
  189. }, permission)
  190. }
  191. export async function doesClipboardItemExists(page: Page): Promise<boolean> {
  192. // Check if WebAPI clipboard supported
  193. return await page.evaluate((): boolean => {
  194. return typeof ClipboardItem !== "undefined"
  195. })
  196. }
  197. export async function getIsWebAPIClipboardSupported(page: Page): Promise<boolean> {
  198. // @ts-ignore "clipboard-write" is not included in TS's type definition for permissionName
  199. return await queryPermission(page, "clipboard-write") && await doesClipboardItemExists(page)
  200. }
  201. export async function navigateToStartOfBlock(page: Page, block: Block) {
  202. const selectionStart = await block.selectionStart()
  203. for (let i = 0; i < selectionStart; i++) {
  204. await page.keyboard.press('ArrowLeft')
  205. }
  206. }