logseq/e2e-tests/utils.ts

209 lines
7.0 KiB
TypeScript
Raw Normal View History

2021-11-29 04:09:01 +00:00
import { Page, Locator } from 'playwright'
import { expect, ConsoleMessage } from '@playwright/test'
import * as pathlib from 'path'
import { modKey } from './util/basic'
// TODO: The file should be a facade of utils in the /util folder
// No more additional functions should be added to this file
// Move the functions to the corresponding files in the /util folder
// Criteria: If the same selector is shared in multiple functions, they should be in the same file
export * from './util/basic'
export * from './util/search-modal'
2023-04-10 08:13:41 +00:00
export * from './util/page'
2022-02-21 00:34:56 +00:00
2021-12-20 08:21:07 +00:00
/**
2021-12-21 00:29:22 +00:00
* Locate the last block in the inner editor
2021-12-20 08:21:07 +00:00
* @param page The Playwright Page object.
* @returns The locator of the last block.
*/
export async function lastBlock(page: Page): Promise<Locator> {
// discard any popups
await page.keyboard.press('Escape')
// click last block
if (await page.locator('text="Click here to edit..."').isVisible()) {
await page.click('text="Click here to edit..."')
} else {
await page.click('.page-blocks-inner .ls-block >> nth=-1')
}
// wait for textarea
await page.waitForSelector('textarea >> nth=0', { state: 'visible' })
await page.waitForTimeout(100)
return page.locator('textarea >> nth=0')
2021-12-21 00:29:22 +00:00
}
/**
* Press Enter and create the next block.
* @param page The Playwright Page object.
*/
export async function enterNextBlock(page: Page): Promise<Locator> {
// Move cursor to the end of the editor
await page.press('textarea >> nth=0', modKey + '+a') // select all
await page.press('textarea >> nth=0', 'ArrowRight')
let blockCount = await page.locator('.page-blocks-inner .ls-block').count()
await page.press('textarea >> nth=0', 'Enter')
2022-04-05 00:41:43 +00:00
await page.waitForTimeout(10)
await page.waitForSelector(`.ls-block >> nth=${blockCount} >> textarea`, { state: 'visible' })
return page.locator('textarea >> nth=0')
}
2021-12-20 08:21:07 +00:00
/**
2021-12-21 00:29:22 +00:00
* Create and locate a new block at the end of the inner editor
2022-01-07 04:09:27 +00:00
* @param page The Playwright Page object
2021-12-20 08:21:07 +00:00
* @returns The locator of the last block
*/
2021-12-21 00:29:22 +00:00
export async function newInnerBlock(page: Page): Promise<Locator> {
await lastBlock(page)
await page.press('textarea >> nth=0', 'Enter')
2021-12-21 00:29:22 +00:00
return page.locator('textarea >> nth=0')
2021-12-21 00:29:22 +00:00
}
2021-12-11 15:50:17 +00:00
export async function escapeToCodeEditor(page: Page): Promise<void> {
await page.press('.block-editor textarea', 'Escape')
await page.waitForSelector('.CodeMirror pre', { state: 'visible' })
2021-12-11 15:50:17 +00:00
await page.waitForTimeout(300)
await page.click('.CodeMirror pre')
await page.waitForTimeout(300)
2021-12-11 15:50:17 +00:00
await page.waitForSelector('.CodeMirror textarea', { state: 'visible' })
2021-12-11 15:50:17 +00:00
}
export async function escapeToBlockEditor(page: Page): Promise<void> {
await page.waitForTimeout(300)
await page.click('.CodeMirror pre')
await page.waitForTimeout(300)
2021-12-11 15:50:17 +00:00
await page.press('.CodeMirror textarea', 'Escape')
await page.waitForTimeout(300)
2021-12-11 15:50:17 +00:00
}
2021-12-30 09:35:20 +00:00
export async function setMockedOpenDirPath(
page: Page,
path?: string
): Promise<void> {
// set next open directory
await page.evaluate(
([path]) => {
Object.assign(window, {
__MOCKED_OPEN_DIR_PATH__: path,
})
},
[path]
)
}
export async function openLeftSidebar(page: Page): Promise<void> {
let sidebar = page.locator('#left-sidebar')
// Left sidebar is toggled by `is-open` class
if (!/is-open/.test(await sidebar.getAttribute('class') || '')) {
await page.click('#left-menu.button')
await page.waitForTimeout(10)
await expect(sidebar).toHaveClass(/is-open/)
}
}
export async function loadLocalGraph(page: Page, path: string): Promise<void> {
await setMockedOpenDirPath(page, path);
2022-09-06 04:21:25 +00:00
const onboardingOpenButton = page.locator('strong:has-text("Choose a folder")')
if (await onboardingOpenButton.isVisible()) {
await onboardingOpenButton.click()
} else {
console.log("No onboarding button, loading file manually")
let sidebar = page.locator('#left-sidebar')
if (!/is-open/.test(await sidebar.getAttribute('class') || '')) {
await page.click('#left-menu.button')
await expect(sidebar).toHaveClass(/is-open/)
}
2022-09-06 04:21:25 +00:00
await page.click('#left-sidebar #repo-switch');
await page.waitForSelector('#left-sidebar .dropdown-wrapper >> text="Add new graph"',
2022-09-06 04:21:25 +00:00
{ state: 'visible', timeout: 5000 })
await page.click('text=Add new graph')
expect(page.locator('#repo-name')).toHaveText(pathlib.basename(path))
}
setMockedOpenDirPath(page, ''); // reset it
await page.waitForSelector(':has-text("Parsing files")', {
state: 'hidden',
timeout: 1000 * 60 * 5,
})
const title = await page.title()
if (title === "Import data into Logseq" || title === "Add another repo") {
await page.click('a.button >> text=Skip')
}
await page.waitForFunction('window.document.title === "Logseq"')
await page.waitForTimeout(500)
// If there is an error notification from a previous test graph being deleted,
// close it first so it doesn't cover up the UI
let n = await page.locator('.notification-close-button').count()
if (n > 1) {
await page.locator('button >> text="Clear all"').click()
} else if (n == 1) {
await page.locator('.notification-close-button').click()
}
await expect(page.locator('.notification-close-button').first()).not.toBeVisible({ timeout: 2000 })
console.log('Graph loaded for ' + path)
}
2022-04-05 01:14:04 +00:00
export async function editFirstBlock(page: Page) {
await page.click('.ls-block .block-content >> nth=0')
}
Core outliner operations refactoring (#4880) * Add outliner nested transact! Copied the code mostly from https://github.com/logseq/logseq/pull/4671 by zhiyuan * refactor: insert-blocks * fix: insert-blocks * fix: move cursor to the last block when inserting * fix: replace the current block when inserting and its content is empty * keep only :insert-blocks * expose only :delete-blocks * Use existing implementations for move-nodes-up-down and indent/outdent. * fix editing state not updated immediately * fix editing status * fix: avoid recursive copy * fix: inserting blocks after an empty block * Implement move-blocks with insert-blocks * fix: block left * Implement move-blocks-up-down with move-blocks * fix: paste text * Implement indent-outdent-blocks with move-blocks * fix: indent/outdent * feat: multiple blocks drag && drop * fix: indent/outdent blocks * fix: drag drop * Port unit tests for outliner.core * enhance: open collapsed parent when indenting blocks * refactor: block selection * fix: indent/outdent blocks with different levels * Add instrument on invalid outliner structure * fix: can't write a block if the page has any outdated blocks * fix: editing status for empty page * fix: multiple drag & drop * fix: drag & drop disallows moving from parents to its child * fix: public property * fix: can't delete first empty block * Remove unused code * fix: e2e tests A workaround is to not select/highlight the block when pressing esc if it has fenced code. * remove unused code * Add batch transaction test * fix: update :block/page when dragging targets' children to another page * Add more tests * Simplify extract * Replace db/get-conn with db/get-db * Simplify extracting blocks from ast * Code cleanup * Code cleanup * Add outliner core fuzzy tests * Remove unused code * fix: cursor not jump to the upper block when pressing Enter in the beginning * fix: Enter in the beginning of a non-empty block * Fix lint warnings * Add editor random e2e tests * Fix typo * enhance: move some fns and add some comments * enhance(outliner): add page-block? util * fix: increase td width to prevent content overflow Signed-off-by: Yue Yang <g1enyy0ung@gmail.com> * First pass at file tests for file-sync Each action usually passes by 5th try * Fix two incorrect calls caught by tests * More test improvements - Easier auth setup - subdirectory is configurable - list graphs api also exercised * Address cleanup from #3839 - Remove unused translation key - Delete or TODO commented code - Capitalize notifications to users * fix quick capture template not working * enhance(sync): add logout * enhance: add logout i18n * fix(plugin): sometimes plugin settings of gui not work when entry from app settings * enable show-brackets? toggle for orgmode [[file:./pages/demo.org][demo]] * fix(sync): fix unfinishable sync loop * feature: logseq protocol; refactor persistGraph * fix: deeplink support * fix: broadcast persist graph on opening new graph with logseq protocol * feat: logseq protocol open action for page-name and uuid * fix: logseq protocol graph param validation * ux: copy logseq URL of block * enhance: remove the redundant 'open' from logseq protocol (v0.1) * ux: page dropdown button for copy page URL * chore: logseq protocol comments * don't create new contents file when changing format Logseq now creates a new contents file when users try to toggle the preferred format, which causes file duplications error. * fix pasting in src block not working on iOS close https://github.com/logseq/logseq/issues/4914 * fix playing video goes into editing mode on iOS * fix copy to clipboard failure on iOS * add Podfile item * fix mobile toolbar order not persisting after restart * test(e2e): add test for backspace and cursor pos (#4896) * test(e2e): add test for backspace and cursor pos * fix(test): refine, fix wrong helper * fix(ui): warn about illegal git commit interval * enhance(editor): allow global git cmd shortcut * style(settings): line-space of general/journals * enhance(editor): accept enter in dummy block Fix #4931 * fix editing state not updated immediately * fix: can't write a block if the page has any outdated blocks TODO: clean outdated blocks * fix: editing status for empty page * Random tree for outliner core tests * Add pre assertions and fn docs based on Zhiyuan's suggestions * Made some changes based on Gabriel's suggestions * fix: tests * fix: save current block before moving * Updated the timeout to 100ms based on llcc's suggestion https://github.com/logseq/logseq/pull/4880#discussion_r851966301 * api-insert-new-block! supports replace-empty-target? * fix: replace all :reuse-last-block? usage Co-authored-by: rcmerci <rcmerci@gmail.com> Co-authored-by: Yue Yang <g1enyy0ung@gmail.com> Co-authored-by: Gabriel Horner <gabriel@logseq.com> Co-authored-by: llcc <lzhes43@gmail.com> Co-authored-by: charlie <xyhp915@qq.com> Co-authored-by: Junyi Du <junyidu.cn@gmail.com> Co-authored-by: Andelf <andelf@gmail.com>
2022-04-19 03:14:38 +00:00
/**
* Wait for a console message with a given prefix to appear, and return the full text of the message
* Or reject after a timeout
*
* @param page
* @param prefix - the prefix to look for
* @param timeout - the timeout in ms
* @returns the full text of the console message
*/
2022-09-06 04:21:25 +00:00
export async function captureConsoleWithPrefix(page: Page, prefix: string, timeout: number = 3000): Promise<string> {
return new Promise((resolve, reject) => {
let console_handler = (msg: ConsoleMessage) => {
let text = msg.text()
if (text.startsWith(prefix)) {
page.removeListener('console', console_handler)
resolve(text.substring(prefix.length))
}
}
page.on('console', console_handler)
setTimeout(reject.bind("timeout"), timeout)
})
}
export async function queryPermission(page: Page, permission: PermissionName): Promise<boolean> {
// Check if WebAPI clipboard supported
return await page.evaluate(async (eval_permission: PermissionName): Promise<boolean> => {
if (typeof navigator.permissions == "undefined")
2022-09-06 04:21:25 +00:00
return Promise.resolve(false);
return navigator.permissions.query({
2022-09-06 04:21:25 +00:00
name: eval_permission
}).then((result: PermissionStatus): boolean => {
return (result.state == "granted" || result.state == "prompt")
2022-09-06 04:21:25 +00:00
})
}, permission)
}
export async function doesClipboardItemExists(page: Page): Promise<boolean> {
// Check if WebAPI clipboard supported
return await page.evaluate((): boolean => {
return typeof ClipboardItem !== "undefined"
})
}
export async function getIsWebAPIClipboardSupported(page: Page): Promise<boolean> {
// @ts-ignore "clipboard-write" is not included in TS's type definition for permissionName
return await queryPermission(page, "clipboard-write") && await doesClipboardItemExists(page)
}