chore: migrate blocksuite test (#9222)

This commit is contained in:
Saul-Mirone
2024-12-20 11:08:21 +00:00
parent f788fdd0a4
commit bfcc53dc1f
325 changed files with 55958 additions and 26 deletions

View File

@@ -0,0 +1,25 @@
import type { Page } from '@playwright/test';
import { waitNextFrame } from './misc.js';
export async function updateBlockType(
page: Page,
flavour: BlockSuite.Flavour,
type?: string
) {
await page.evaluate(
([flavour, type]) => {
window.host.std.command
.chain()
.updateBlockType({
flavour,
props: {
type,
},
})
.run();
},
[flavour, type] as [BlockSuite.Flavour, string?]
);
await waitNextFrame(page, 400);
}

View File

@@ -0,0 +1,130 @@
import type { IPoint } from '@blocksuite/global/utils';
import type { Page } from '@playwright/test';
import { toViewCoord } from './edgeless.js';
import { waitNextFrame } from './misc.js';
export function getDebugMenu(page: Page) {
const debugMenu = page.locator('starter-debug-menu');
return {
debugMenu,
undoBtn: debugMenu.locator('sl-tooltip[content="Undo"]'),
redoBtn: debugMenu.locator('sl-tooltip[content="Redo"]'),
blockTypeButton: debugMenu.getByRole('button', { name: 'Block Type' }),
testOperationsButton: debugMenu.getByRole('button', {
name: 'Test Operations',
}),
pagesBtn: debugMenu.getByTestId('docs-button'),
};
}
export async function moveView(page: Page, point: [number, number]) {
const [x, y] = await toViewCoord(page, point);
await page.mouse.move(x, y);
}
export async function click(page: Page, point: IPoint) {
await page.mouse.click(point.x, point.y);
}
export async function clickView(page: Page, point: [number, number]) {
const [x, y] = await toViewCoord(page, point);
await page.mouse.click(x, y);
}
export async function dblclickView(page: Page, point: [number, number]) {
const [x, y] = await toViewCoord(page, point);
await page.mouse.dblclick(x, y);
}
export async function undoByClick(page: Page) {
await getDebugMenu(page).undoBtn.click();
}
export async function redoByClick(page: Page) {
await getDebugMenu(page).redoBtn.click();
}
export async function clickBlockById(page: Page, id: string) {
await page.click(`[data-block-id="${id}"]`);
}
export async function doubleClickBlockById(page: Page, id: string) {
await page.dblclick(`[data-block-id="${id}"]`);
}
export async function disconnectByClick(page: Page) {
await clickTestOperationsMenuItem(page, 'Disconnect');
}
export async function connectByClick(page: Page) {
await clickTestOperationsMenuItem(page, 'Connect');
}
export async function addNoteByClick(page: Page) {
await clickTestOperationsMenuItem(page, 'Add Note');
}
export async function addNewPage(page: Page) {
const { pagesBtn } = getDebugMenu(page);
if (!(await page.locator('docs-panel').isVisible())) {
await pagesBtn.click();
}
await page.locator('.new-doc-button').click();
const docMetas = await page.evaluate(() => {
const { collection } = window;
return collection.meta.docMetas;
});
if (!docMetas.length) throw new Error('Add new doc failed');
return docMetas[docMetas.length - 1];
}
export async function switchToPage(page: Page, docId?: string) {
await page.evaluate(docId => {
const { collection, editor } = window;
if (!docId) {
const docMetas = collection.meta.docMetas;
if (!docMetas.length) return;
docId = docMetas[0].id;
}
const doc = collection.getDoc(docId);
if (!doc) return;
editor.doc = doc;
}, docId);
}
export async function clickTestOperationsMenuItem(page: Page, name: string) {
const menuButton = getDebugMenu(page).testOperationsButton;
await menuButton.click();
await waitNextFrame(page); // wait for animation ended
const menuItem = page.getByRole('menuitem', { name });
await menuItem.click();
await menuItem.waitFor({ state: 'hidden' }); // wait for animation ended
}
export async function switchReadonly(page: Page, value = true) {
await page.evaluate(_value => {
const defaultPage = document.querySelector(
'affine-page-root'
) as HTMLElement & {
doc: {
awarenessStore: { setFlag: (key: string, value: unknown) => void };
};
};
const doc = defaultPage.doc;
doc.awarenessStore.setFlag('readonly', { 'doc:home': _value });
}, value);
}
export async function activeEmbed(page: Page) {
await page.click('.resizable-img');
}
export async function toggleDarkMode(page: Page) {
await page.click('sl-tooltip[content="Toggle Dark Mode"] sl-button');
}

View File

@@ -0,0 +1,271 @@
import type { Page } from '@playwright/test';
import { assertImageOption } from 'utils/asserts.js';
import { getIndexCoordinate, waitNextFrame } from './misc.js';
export async function dragBetweenCoords(
page: Page,
from: { x: number; y: number },
to: { x: number; y: number },
options?: {
beforeMouseUp?: () => Promise<void>;
steps?: number;
click?: boolean;
button?: 'left' | 'right' | 'middle';
}
) {
const steps = options?.steps ?? 20;
const button: 'left' | 'right' | 'middle' = options?.button ?? 'left';
const { x: x1, y: y1 } = from;
const { x: x2, y: y2 } = to;
options?.click && (await page.mouse.click(x1, y1));
await page.mouse.move(x1, y1);
await page.mouse.down({ button });
await page.mouse.move(x2, y2, { steps });
await options?.beforeMouseUp?.();
await page.mouse.up({ button });
}
export async function dragBetweenIndices(
page: Page,
[startRichTextIndex, startVIndex]: [number, number],
[endRichTextIndex, endVIndex]: [number, number],
startCoordOffSet: { x: number; y: number } = { x: 0, y: 0 },
endCoordOffSet: { x: number; y: number } = { x: 0, y: 0 },
options?: {
beforeMouseUp?: () => Promise<void>;
steps?: number;
click?: boolean;
}
) {
const finalOptions = {
steps: 50,
...options,
};
const startCoord = await getIndexCoordinate(
page,
[startRichTextIndex, startVIndex],
startCoordOffSet
);
const endCoord = await getIndexCoordinate(
page,
[endRichTextIndex, endVIndex],
endCoordOffSet
);
await dragBetweenCoords(page, startCoord, endCoord, finalOptions);
}
export async function dragOverTitle(page: Page) {
const { from, to } = await page.evaluate(() => {
const titleInput = document.querySelector(
'doc-title rich-text'
) as HTMLTextAreaElement;
const titleBound = titleInput.getBoundingClientRect();
return {
from: { x: titleBound.left + 1, y: titleBound.top + 1 },
to: { x: titleBound.right - 1, y: titleBound.bottom - 1 },
};
});
await dragBetweenCoords(page, from, to, {
steps: 5,
});
}
export async function dragEmbedResizeByTopRight(page: Page) {
const { from, to } = await page.evaluate(() => {
const bottomRightButton = document.querySelector(
'.top-right'
) as HTMLInputElement;
const bottomRightButtonBound = bottomRightButton.getBoundingClientRect();
const y = bottomRightButtonBound.top;
return {
from: { x: bottomRightButtonBound.left + 5, y: y + 5 },
to: { x: bottomRightButtonBound.left + 5 - 200, y },
};
});
await dragBetweenCoords(page, from, to, {
steps: 10,
});
}
export async function dragEmbedResizeByTopLeft(page: Page) {
const { from, to } = await page.evaluate(() => {
const bottomRightButton = document.querySelector(
'.top-left'
) as HTMLInputElement;
const bottomRightButtonBound = bottomRightButton.getBoundingClientRect();
const y = bottomRightButtonBound.top;
return {
from: { x: bottomRightButtonBound.left + 5, y: y + 5 },
to: { x: bottomRightButtonBound.left + 5 + 200, y },
};
});
await dragBetweenCoords(page, from, to, {
steps: 10,
});
}
export async function dragHandleFromBlockToBlockBottomById(
page: Page,
sourceId: string,
targetId: string,
bottom = true,
offset?: number,
beforeMouseUp?: () => Promise<void>
) {
const sourceBlock = await page
.locator(`[data-block-id="${sourceId}"]`)
.boundingBox();
const targetBlock = await page
.locator(`[data-block-id="${targetId}"]`)
.boundingBox();
if (!sourceBlock || !targetBlock) {
throw new Error();
}
await page.mouse.move(
sourceBlock.x + sourceBlock.width / 2,
sourceBlock.y + sourceBlock.height / 2
);
await waitNextFrame(page);
const dragHandleContainer = page.locator('.affine-drag-handle-container');
await dragHandleContainer.hover();
const handle = await dragHandleContainer.boundingBox();
if (!handle) {
throw new Error();
}
await page.mouse.move(
handle.x + handle.width / 2,
handle.y + handle.height / 2,
{ steps: 10 }
);
await page.mouse.down();
await page.mouse.move(
targetBlock.x,
targetBlock.y + (bottom ? targetBlock.height - 1 : 1),
{
steps: 50,
}
);
if (offset) {
await page.mouse.move(
targetBlock.x + offset,
targetBlock.y + (bottom ? targetBlock.height - 1 : 1),
{
steps: 50,
}
);
}
if (beforeMouseUp) {
await beforeMouseUp();
}
await page.mouse.up();
}
export async function dragBlockToPoint(
page: Page,
sourceId: string,
point: { x: number; y: number }
) {
const sourceBlock = await page
.locator(`[data-block-id="${sourceId}"]`)
.boundingBox();
if (!sourceBlock) {
throw new Error();
}
await page.mouse.move(
sourceBlock.x + sourceBlock.width / 2,
sourceBlock.y + sourceBlock.height / 2
);
const handle = await page
.locator('.affine-drag-handle-container')
.boundingBox();
if (!handle) {
throw new Error();
}
await page.mouse.move(
handle.x + handle.width / 2,
handle.y + handle.height / 2
);
await page.mouse.down();
await page.mouse.move(point.x, point.y, {
steps: 50,
});
await page.mouse.up();
}
export async function moveToImage(page: Page) {
const { x, y } = await page.evaluate(() => {
const bottomRightButton = document.querySelector('img') as HTMLElement;
const imageClient = bottomRightButton.getBoundingClientRect();
const y = imageClient.top;
return {
x: imageClient.left + 30,
y: y + 30,
};
});
await page.mouse.move(x, y);
}
export async function popImageMoreMenu(page: Page) {
await moveToImage(page);
await assertImageOption(page);
const moreButton = page.locator('.image-toolbar-button.more');
await moreButton.click();
const menu = page.locator('.image-more-popup-menu');
const turnIntoCardButton = page.locator('editor-menu-action', {
hasText: 'Turn into card view',
});
const copyButton = page.locator('editor-menu-action', {
hasText: 'Copy',
});
const duplicateButton = page.locator('editor-menu-action', {
hasText: 'Duplicate',
});
const deleteButton = page.locator('editor-menu-action', {
hasText: 'Delete',
});
return {
menu,
copyButton,
turnIntoCardButton,
duplicateButton,
deleteButton,
};
}
export async function clickBlockDragHandle(page: Page, blockId: string) {
const blockBox = await page
.locator(`[data-block-id="${blockId}"]`)
.boundingBox();
if (!blockBox) {
throw new Error();
}
await page.mouse.move(
blockBox.x + blockBox.width / 2,
blockBox.y + blockBox.height / 2
);
const handleBox = await page
.locator('.affine-drag-handle-container')
.boundingBox();
if (!handleBox) {
throw new Error();
}
await page.mouse.click(
handleBox.x + handleBox.width / 2,
handleBox.y + handleBox.height / 2
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,7 @@
export * from './block.js';
export * from './click.js';
export * from './drag.js';
export * from './edgeless.js';
export * from './keyboard.js';
export * from './misc.js';
export * from './selection.js';

View File

@@ -0,0 +1,241 @@
import type { Page } from '@playwright/test';
const IS_MAC = process.platform === 'darwin';
// const IS_WINDOWS = process.platform === 'win32';
// const IS_LINUX = !IS_MAC && !IS_WINDOWS;
/**
* The key will be 'Meta' on Macs and 'Control' on other platforms
* @example
* ```ts
* await page.keyboard.press(`${SHORT_KEY}+a`);
* ```
*/
export const SHORT_KEY = IS_MAC ? 'Meta' : 'Control';
/**
* The key will be 'Alt' on Macs and 'Shift' on other platforms
* @example
* ```ts
* await page.keyboard.press(`${SHORT_KEY}+${MODIFIER_KEY}+1`);
* ```
*/
export const MODIFIER_KEY = IS_MAC ? 'Alt' : 'Shift';
export const SHIFT_KEY = 'Shift';
export async function type(page: Page, content: string, delay = 20) {
await page.keyboard.type(content, { delay });
}
export async function withPressKey(
page: Page,
key: string,
fn: () => Promise<void>
) {
await page.keyboard.down(key);
await fn();
await page.keyboard.up(key);
}
export async function defaultTool(page: Page) {
await page.keyboard.press('v', { delay: 20 });
}
export async function pressBackspace(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press('Backspace', { delay: 20 });
}
}
export async function pressSpace(page: Page) {
await page.keyboard.press('Space', { delay: 20 });
}
export async function pressArrowLeft(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press('ArrowLeft', { delay: 20 });
}
}
export async function pressArrowRight(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press('ArrowRight', { delay: 20 });
}
}
export async function pressArrowDown(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press('ArrowDown', { delay: 20 });
}
}
export async function pressArrowUp(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press('ArrowUp', { delay: 20 });
}
}
export async function pressArrowDownWithShiftKey(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press(`${SHIFT_KEY}+ArrowDown`, { delay: 20 });
}
}
export async function pressArrowUpWithShiftKey(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press(`${SHIFT_KEY}+ArrowUp`, { delay: 20 });
}
}
export async function pressEnter(page: Page, count = 1) {
// avoid flaky test by simulate real user input
for (let i = 0; i < count; i++) {
await page.keyboard.press('Enter', { delay: 30 });
}
}
export async function pressEnterWithShortkey(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+Enter`, { delay: 20 });
}
export async function pressEscape(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press('Escape', { delay: 20 });
}
}
export async function undoByKeyboard(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+z`, { delay: 20 });
}
export async function formatType(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+${MODIFIER_KEY}+1`, {
delay: 20,
});
}
export async function redoByKeyboard(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+Shift+Z`, { delay: 20 });
}
export async function selectAllByKeyboard(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+a`, {
delay: 20,
});
}
export async function selectAllBlocksByKeyboard(page: Page) {
for (let i = 0; i < 3; i++) {
await selectAllByKeyboard(page);
}
}
export async function pressTab(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press('Tab', { delay: 20 });
}
}
export async function pressShiftTab(page: Page) {
await page.keyboard.press('Shift+Tab', { delay: 20 });
}
export async function pressBackspaceWithShortKey(page: Page, count = 1) {
for (let i = 0; i < count; i++) {
await page.keyboard.press(`${SHORT_KEY}+Backspace`, { delay: 20 });
}
}
export async function pressShiftEnter(page: Page) {
await page.keyboard.press('Shift+Enter', { delay: 20 });
}
export async function inlineCode(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+e`, { delay: 20 });
}
export async function strikethrough(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+Shift+s`, { delay: 20 });
}
export async function copyByKeyboard(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+c`, { delay: 20 });
}
export async function cutByKeyboard(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+x`, { delay: 20 });
}
/**
* Notice: this method will try to click closest editor by default
*/
export async function pasteByKeyboard(page: Page, forceFocus = true) {
if (forceFocus) {
const isEditorActive = await page.evaluate(() =>
document.activeElement?.closest('affine-editor-container')
);
if (!isEditorActive) {
await page.click('affine-editor-container');
}
}
await page.keyboard.press(`${SHORT_KEY}+v`, { delay: 20 });
}
export async function createCodeBlock(page: Page) {
await page.keyboard.press(`${SHORT_KEY}+Alt+c`);
}
export async function getCursorBlockIdAndHeight(
page: Page
): Promise<[string | null, number | null]> {
return page.evaluate(() => {
const selection = window.getSelection() as Selection;
const range = selection.getRangeAt(0);
const startContainer =
range.startContainer instanceof Text
? (range.startContainer.parentElement as HTMLElement)
: (range.startContainer as HTMLElement);
const startComponent = startContainer.closest(`[data-block-id]`);
const { height } = (startComponent as HTMLElement).getBoundingClientRect();
const id = (startComponent as HTMLElement).dataset.blockId!;
return [id, height];
});
}
/**
* fill a line by keep triggering key input
* @param page
* @param toNext if true, fill until soft wrap
*/
export async function fillLine(page: Page, toNext = false) {
const [id, height] = await getCursorBlockIdAndHeight(page);
if (id && height) {
let nextHeight;
// type until current block height is changed, means has new line
do {
await page.keyboard.type('a', { delay: 20 });
[, nextHeight] = await getCursorBlockIdAndHeight(page);
} while (nextHeight === height);
if (!toNext) {
await page.keyboard.press('Backspace');
}
}
}
export async function pressForwardDelete(page: Page) {
if (IS_MAC) {
await page.keyboard.press('Control+d', { delay: 20 });
} else {
await page.keyboard.press('Delete', { delay: 20 });
}
}
export async function pressForwardDeleteWord(page: Page) {
if (IS_MAC) {
await page.keyboard.press('Alt+Delete', { delay: 20 });
} else {
await page.keyboard.press('Control+Delete', { delay: 20 });
}
}

View File

@@ -0,0 +1,70 @@
import { expect, type Page } from '@playwright/test';
import { pressEnter, type } from './keyboard.js';
export function getLinkedDocPopover(page: Page) {
const REFERENCE_NODE = ' ' as const;
const refNode = page.locator('affine-reference');
const linkedDocPopover = page.locator('.linked-doc-popover');
const pageBtn = linkedDocPopover.locator('.group > icon-button');
const findRefNode = async (title: string) => {
const refNode = page.locator(`affine-reference`, {
has: page.locator(`.affine-reference-title[data-title="${title}"]`),
});
await expect(refNode).toBeVisible();
return refNode;
};
const assertExistRefText = async (text: string) => {
await expect(refNode).toBeVisible();
const refTitleNode = refNode.locator('.affine-reference-title');
// Since the text is in the pseudo element
// we need to use `toHaveAttribute` to assert it.
// And it's not a good strict way to assert the text.
await expect(refTitleNode).toHaveAttribute('data-title', text);
};
const createDoc = async (
pageType: 'LinkedPage' | 'Subpage',
pageName?: string
) => {
await type(page, '@');
await expect(linkedDocPopover).toBeVisible();
if (pageName) {
await type(page, pageName);
} else {
pageName = 'Untitled';
}
await page.keyboard.press('ArrowUp');
if (pageType === 'LinkedPage') {
await page.keyboard.press('ArrowUp');
}
await pressEnter(page);
return findRefNode(pageName);
};
const assertActivePageIdx = async (idx: number) => {
if (idx !== 0) {
await expect(pageBtn.nth(0)).toHaveAttribute('hover', 'false');
}
await expect(pageBtn.nth(idx)).toHaveAttribute('hover', 'true');
};
return {
REFERENCE_NODE,
linkedDocPopover,
refNode,
pageBtn,
findRefNode,
assertExistRefText,
createLinkedDoc: async (pageName?: string) =>
createDoc('LinkedPage', pageName),
/**
* @deprecated
*/
createSubpage: async (pageName?: string) => createDoc('Subpage', pageName),
assertActivePageIdx,
};
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,45 @@
import type { Page } from '@playwright/test';
export async function getRichTextBoundingBox(
page: Page,
blockId: string
): Promise<DOMRect> {
return page.evaluate(id => {
const paragraph = document.querySelector(
`[data-block-id="${id}"] .inline-editor`
);
const bbox = paragraph?.getBoundingClientRect() as DOMRect;
return bbox;
}, blockId);
}
interface Rect {
x: number;
y: number;
width: number;
height: number;
}
export async function clickInEdge(page: Page, rect: Rect) {
const edgeX = rect.x + rect.width / 2;
const edgeY = rect.y + rect.height - 5;
await page.mouse.click(edgeX, edgeY);
}
export async function clickInCenter(page: Page, rect: Rect) {
const centerX = rect.x + rect.width / 2;
const centerY = rect.y + rect.height / 2;
await page.mouse.click(centerX, centerY);
}
export async function getBoundingRect(
page: Page,
selector: string
): Promise<Rect> {
const div = page.locator(selector);
const boundingRect = await div.boundingBox();
if (!boundingRect) {
throw new Error(`Missing ${selector}`);
}
return boundingRect;
}