test(editor): move blocksuite test to tests folder (#10917)

This commit is contained in:
Saul-Mirone
2025-03-17 06:40:25 +00:00
parent 0f83566504
commit d5a5df5e49
352 changed files with 47 additions and 44 deletions
@@ -0,0 +1,25 @@
import type { Page } from '@playwright/test';
import { waitNextFrame } from './misc.js';
export async function updateBlockType(
page: Page,
flavour: string,
type?: string
) {
await page.evaluate(
([flavour, type]) => {
window.host.std.command.exec(
window.$blocksuite.blocks.note.updateBlockType,
{
flavour,
props: {
type,
},
}
);
},
[flavour, type] as [string, string?]
);
await waitNextFrame(page, 400);
}
+129
View File
@@ -0,0 +1,129 @@
import type { IPoint } from '@blocksuite/global/gfx';
import type { Store } from '@blocksuite/store';
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,affine-edgeless-root'
) as HTMLElement & {
doc: Store;
};
const doc = defaultPage.doc;
doc.readonly = _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');
}
+273
View File
@@ -0,0 +1,273 @@
import type { Page } from '@playwright/test';
import { assertImageOption } from '../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(
'affine-image 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
@@ -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';
@@ -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 });
}
}
@@ -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
@@ -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;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,77 @@
import { clamp } from '@blocksuite/global/gfx';
export const BLOCK_CHILDREN_CONTAINER_PADDING_LEFT = 24;
export const NOTE_MIN_WIDTH = 450 + 24 * 2;
export const NOTE_MIN_HEIGHT = 92;
export const DEFAULT_NOTE_WIDTH = NOTE_MIN_WIDTH;
export const DEFAULT_NOTE_HEIGHT = NOTE_MIN_HEIGHT;
export enum NoteDisplayMode {
DocAndEdgeless = 'both',
DocOnly = 'doc',
EdgelessOnly = 'edgeless',
}
export const bound01 = (n: number, max: number) => {
n = clamp(0, n, max);
// Handle floating point rounding errors
if (Math.abs(n - max) < 0.000001) {
return 1;
}
// Convert into [0, 1] range if it isn't already
return (n % max) / max;
};
export const parseHexToRgba = (hex: string) => {
if (hex.startsWith('#')) {
hex = hex.substring(1);
}
const len = hex.length;
let arr: string[] = [];
if (len === 3 || len === 4) {
arr = hex.split('').map(s => s.repeat(2));
} else if (len === 6 || len === 8) {
arr = Array.from<number>({ length: len / 2 })
.fill(0)
.map((n, i) => n + i * 2)
.map(n => hex.substring(n, n + 2));
}
const [r, g, b, a = 1] = arr
.map(s => parseInt(s, 16))
.map(n => bound01(n, 255));
return { r, g, b, a };
};
export const parseStringToRgba = (value: string) => {
value = value.trim();
// Compatible old format: `--affine-palette-transparent`
if (value.endsWith('transparent')) {
return { r: 1, g: 1, b: 1, a: 0 };
}
if (value.startsWith('#')) {
return parseHexToRgba(value);
}
if (value.startsWith('rgb')) {
const [r, g, b, a = 1] = value
.replace(/^rgba?/, '')
.replace(/\(|\)/, '')
.split(',')
.map(s => parseFloat(s.trim()))
// In CSS, the alpha is already in the range [0, 1]
.map((n, i) => bound01(n, i === 3 ? 1 : 255));
return { r, g, b, a };
}
return { r: 0, g: 0, b: 0, a: 1 };
};
@@ -0,0 +1,32 @@
import type { EditorHost } from '@blocksuite/affine/block-std';
import type * as Effects from '@blocksuite/affine/effects';
import type { Store, Transformer, Workspace } from '@blocksuite/affine/store';
import type { TestAffineEditorContainer } from '@blocksuite/integration-test';
declare const _GLOBAL_: typeof Effects;
declare global {
interface Window {
/** Available on playground window
* the following instance are initialized in `packages/playground/apps/starter/main.ts`
*/
$blocksuite: {
store: typeof import('@blocksuite/affine/store');
blocks: {
database: typeof import('@blocksuite/affine/blocks/database');
note: typeof import('@blocksuite/affine/blocks/note');
};
global: {
utils: typeof import('@blocksuite/affine/global/utils');
};
services: typeof import('@blocksuite/affine/shared/services');
editor: typeof import('@blocksuite/integration-test');
blockStd: typeof import('@blocksuite/affine/block-std');
};
collection: Workspace;
doc: Store;
editor: TestAffineEditorContainer;
host: EditorHost;
job: Transformer;
}
}
+28
View File
@@ -0,0 +1,28 @@
import type { BlockSnapshot } from '@blocksuite/store';
export function ignoreFields(target: unknown, keys: string[]): unknown {
if (Array.isArray(target)) {
return target.map((item: unknown) => ignoreFields(item, keys));
} else if (typeof target === 'object' && target !== null) {
return Object.keys(target).reduce(
(acc: Record<string, unknown>, key: string) => {
if (keys.includes(key)) {
acc[key] = '*';
} else {
acc[key] = ignoreFields(
(target as Record<string, unknown>)[key],
keys
);
}
return acc;
},
{}
);
}
return target;
}
export function ignoreSnapshotId(snapshot: BlockSnapshot) {
const ignored = ignoreFields(snapshot, ['id']);
return JSON.stringify(ignored, null, 2);
}
@@ -0,0 +1,22 @@
import type { Page } from '@playwright/test';
export async function getStringFromRichText(
page: Page,
index = 0
): Promise<string> {
await page.waitForTimeout(50);
return page.evaluate(
([index]) => {
const editorHost = document.querySelector('editor-host');
const richTexts = editorHost?.querySelectorAll('rich-text');
if (!richTexts) {
throw new Error('Cannot find rich-text');
}
const editor = (richTexts[index] as any).inlineEditor;
return editor.yText.toString();
},
[index]
);
}
+130
View File
@@ -0,0 +1,130 @@
import type {
MindmapElementModel,
MindmapNode,
ShapeElementModel,
} from '@blocksuite/affine/model';
import type { Page } from '@playwright/test';
import { clickView } from './actions/click.js';
export async function createMindMap(page: Page, coords: [number, number]) {
await page.keyboard.press('m');
await clickView(page, coords);
const id = await page.evaluate(() => {
const edgelessBlock = document.querySelector('affine-edgeless-root');
if (!edgelessBlock) {
throw new Error('edgeless block not found');
}
const mindmaps = edgelessBlock.gfx.gfxElements.filter(
el => 'type' in el && el.type === 'mindmap'
);
return mindmaps[mindmaps.length - 1].id;
});
return id;
}
export async function getMindMapNode(
page: Page,
mindmapId: string,
pathOrId: number[] | string
) {
return page.evaluate(
({ mindmapId, pathOrId }) => {
const edgelessBlock = document.querySelector('affine-edgeless-root');
if (!edgelessBlock) {
throw new Error('edgeless block not found');
}
const mindmap = edgelessBlock.gfx.getElementById(
mindmapId
) as MindmapElementModel;
if (!mindmap) {
throw new Error(`Mindmap not found: ${mindmapId}`);
}
const node = Array.isArray(pathOrId)
? mindmap.getNodeByPath(pathOrId)
: mindmap.getNode(pathOrId);
if (!node) {
throw new Error(`Mindmap node not found at: ${pathOrId}`);
}
const rect = edgelessBlock.gfx.viewport.toViewBound(
node.element.elementBound
);
return {
path: mindmap.getPath(node),
id: node.id,
text: (node.element as ShapeElementModel).text?.toString() ?? '',
rect: {
x: rect.x,
y: rect.y,
w: rect.w,
h: rect.h,
},
};
},
{
mindmapId,
pathOrId,
}
);
}
type NewNodeInfo = {
text: string;
children?: NewNodeInfo[];
};
export async function addMindmapNodes(
page: Page,
mindmapId: string,
path: number[],
newNode: NewNodeInfo
) {
return page.evaluate(
({ mindmapId, path, newNode }) => {
const edgelessBlock = document.querySelector('affine-edgeless-root');
if (!edgelessBlock) {
throw new Error('edgeless block not found');
}
const mindmap = edgelessBlock.gfx.getElementById(
mindmapId
) as MindmapElementModel;
if (!mindmap) {
throw new Error(`Mindmap not found: ${mindmapId}`);
}
const parent = mindmap.getNodeByPath(path);
if (!parent) {
throw new Error(`Mindmap node not found at: ${path}`);
}
const addNode = (
mindmap: MindmapElementModel,
node: NewNodeInfo,
parent: MindmapNode
) => {
const newNodeId = mindmap.addNode(parent, undefined, undefined, {
text: node.text,
});
if (node.children) {
node.children.forEach(child => {
addNode(mindmap, child, mindmap.getNode(newNodeId)!);
});
}
return newNodeId;
};
return addNode(mindmap, newNode, parent);
},
{ mindmapId, path, newNode }
);
}
@@ -0,0 +1,15 @@
import process from 'node:process';
const editorIndex = {
0: 0,
1: 1,
}[process.env.MULTIPLE_EDITOR_INDEX ?? ''];
export const scope =
editorIndex == null
? undefined
: editorIndex === 0
? 'FIRST | '
: 'SECOND | ';
export const multiEditor = scope != null;
export const currentEditorIndex = editorIndex ?? 0;
+57
View File
@@ -0,0 +1,57 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { test as baseTest } from '@playwright/test';
import { scope } from './multiple-editor.js';
const istanbulTempDir = process.env.ISTANBUL_TEMP_DIR
? path.resolve(process.env.ISTANBUL_TEMP_DIR)
: path.join(process.cwd(), '.nyc_output');
function generateUUID() {
return crypto.randomUUID();
}
const enableCoverage = !!process.env.CI || !!process.env.COVERAGE;
export const scoped = (stringsArray: TemplateStringsArray) => {
return `${scope ?? ''}${stringsArray.join()}`;
};
export const test = baseTest.extend<{}>({
context: async ({ context }, use) => {
if (enableCoverage) {
await context.addInitScript(() =>
window.addEventListener('beforeunload', () =>
// @ts-expect-error
window.collectIstanbulCoverage(JSON.stringify(window.__coverage__))
)
);
await fs.promises.mkdir(istanbulTempDir, { recursive: true });
await context.exposeFunction(
'collectIstanbulCoverage',
(coverageJSON?: string) => {
if (coverageJSON)
fs.writeFileSync(
path.join(
istanbulTempDir,
`playwright_coverage_${generateUUID()}.json`
),
coverageJSON
);
}
);
}
await use(context);
if (enableCoverage) {
for (const page of context.pages()) {
await page.evaluate(() =>
// @ts-expect-error
window.collectIstanbulCoverage(JSON.stringify(window.__coverage__))
);
}
}
},
});
+123
View File
@@ -0,0 +1,123 @@
import { expect, type Page } from '@playwright/test';
import { waitNextFrame } from './actions/misc.js';
import { assertAlmostEqual } from './asserts.js';
export function getFormatBar(page: Page) {
const formatBar = page.locator('affine-toolbar-widget editor-toolbar');
const boldBtn = formatBar.getByTestId('bold');
const italicBtn = formatBar.getByTestId('italic');
const underlineBtn = formatBar.getByTestId('underline');
const strikeBtn = formatBar.getByTestId('strike');
const codeBtn = formatBar.getByTestId('code');
const linkBtn = formatBar.getByTestId('link');
// highlight
const highlightBtn = formatBar.getByRole('button', { name: 'highlight' });
const redForegroundBtn = formatBar.getByTestId('foreground-red');
const createLinkedDocBtn = formatBar.getByTestId('convert-to-linked-doc');
const defaultColorBtn = formatBar.getByTestId('foreground-default');
const highlight = {
highlightBtn,
redForegroundBtn,
defaultColorBtn,
};
const paragraphBtn = formatBar.getByRole('button', { name: 'Conversions' });
const openParagraphMenu = async () => {
await expect(formatBar).toBeVisible();
await paragraphBtn.click();
};
const textBtn = formatBar.getByRole('button', { name: 'Text' });
const h1Btn = formatBar.getByRole('button', { name: 'Heading 1' });
const bulletedBtn = formatBar.getByRole('button', { name: 'Bulleted List' });
const codeBlockBtn = formatBar.getByRole('button', { name: 'Code Block' });
const moreBtn = formatBar.getByRole('button', { name: 'More' });
const copyBtn = formatBar.getByRole('button', { name: 'Copy' });
const duplicateBtn = formatBar.getByRole('button', { name: 'Duplicate' });
const deleteBtn = formatBar.getByRole('button', { name: 'Delete' });
const openMoreMenu = async () => {
await expect(formatBar).toBeVisible();
await moreBtn.click();
};
const assertBoundingBox = async (x: number, y: number) => {
const boundingBox = await formatBar.boundingBox();
if (!boundingBox) {
throw new Error("formatBar doesn't exist");
}
assertAlmostEqual(boundingBox.x, x, 6);
assertAlmostEqual(boundingBox.y, y, 6);
};
return {
formatBar,
boldBtn,
italicBtn,
underlineBtn,
strikeBtn,
codeBtn,
linkBtn,
highlight,
createLinkedDocBtn,
openParagraphMenu,
textBtn,
h1Btn,
bulletedBtn,
codeBlockBtn,
moreBtn,
openMoreMenu,
copyBtn,
duplicateBtn,
deleteBtn,
assertBoundingBox,
};
}
export function getEmbedCardToolbar(page: Page) {
const embedCardToolbar = page.locator('affine-toolbar-widget editor-toolbar');
function createButtonLocator(name: string) {
return embedCardToolbar.getByRole('button', { name });
}
const copyButton = createButtonLocator('copy-link');
const editButton = createButtonLocator('edit');
const cardStyleButton = createButtonLocator('card style');
const captionButton = createButtonLocator('caption');
const moreButton = createButtonLocator('more');
const cardStyleHorizontalButton = embedCardToolbar.getByRole('button', {
name: 'Large horizontal style',
});
const cardStyleListButton = embedCardToolbar.getByRole('button', {
name: 'Small horizontal style',
});
const openCardStyleMenu = async () => {
await expect(embedCardToolbar).toBeVisible();
await cardStyleButton.click();
await waitNextFrame(page);
};
const openMoreMenu = async () => {
await expect(embedCardToolbar).toBeVisible();
await moreButton.click();
await waitNextFrame(page);
};
return {
embedCardToolbar,
copyButton,
editButton,
cardStyleButton,
captionButton,
moreButton,
openCardStyleMenu,
openMoreMenu,
cardStyleHorizontalButton,
cardStyleListButton,
};
}