image-preview-edit.test.mjs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import assert from "node:assert/strict";
  2. import { before, after, test } from "node:test";
  3. import { fileURLToPath } from "node:url";
  4. import { mkdir } from "node:fs/promises";
  5. import { join } from "node:path";
  6. import { createServer } from "vite";
  7. import react from "@vitejs/plugin-react";
  8. import tailwindcss from "@tailwindcss/vite";
  9. import { chromium } from "playwright-core";
  10. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  11. const entry = "/packages/ui/test/browser/manual-review/pending/image-preview-edit.fixture.tsx";
  12. const artifacts = join(root, "packages/desktop/.e2e-artifacts/image-preview-edit-browser");
  13. let server, browser, origin;
  14. before(async () => {
  15. await mkdir(artifacts, { recursive: true });
  16. server = await createServer({
  17. root,
  18. configFile: false,
  19. plugins: [
  20. {
  21. name: "image-actions-fixture",
  22. enforce: "pre",
  23. configureServer(vite) {
  24. vite.middlewares.use(async (req, res, next) => {
  25. if (!req.url?.startsWith("/fixture?")) return next();
  26. res.setHeader("Content-Type", "text/html");
  27. res.end(
  28. await vite.transformIndexHtml(
  29. req.url,
  30. `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"/></head><body><div id="root"></div><script type="module" src="${entry}"></script></body></html>`,
  31. ),
  32. );
  33. });
  34. },
  35. },
  36. react(),
  37. tailwindcss(),
  38. ],
  39. resolve: { alias: { "@": `${root}packages/ui/src` } },
  40. optimizeDeps: { entries: [entry.slice(1)] },
  41. server: {
  42. host: "127.0.0.1",
  43. port: 0,
  44. hmr: false,
  45. watch: { ignored: ["**/packages/desktop/out/**", "**/.e2e-artifacts/**"] },
  46. },
  47. });
  48. await server.listen();
  49. origin = server.resolvedUrls.local[0];
  50. browser = await chromium.launch(
  51. process.env.CHROME_EXECUTABLE_PATH
  52. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  53. : { channel: "chrome" },
  54. );
  55. });
  56. after(async () => {
  57. await browser?.close();
  58. await server?.close();
  59. });
  60. async function openPreview(page, query = "locale=zh-CN") {
  61. await page.goto(`${origin}fixture?${query}`);
  62. await page.getByRole("button", { name: "Open", exact: true }).click();
  63. await page.waitForFunction(
  64. () => document.querySelector('[role="dialog"] img')?.naturalWidth === 1200,
  65. );
  66. await page.locator('[role="dialog"]').evaluate(async (el) => {
  67. await Promise.all(el.getAnimations().map((a) => a.finished));
  68. });
  69. }
  70. test("IPE01 blank closes but image does not", async () => {
  71. const page = await browser.newPage({ viewport: { width: 1100, height: 844 } });
  72. try {
  73. await openPreview(page);
  74. await page.locator('[role="dialog"] img').click();
  75. assert.equal(await page.locator('[role="dialog"]').count(), 1);
  76. await page.mouse.click(40, 400);
  77. await page.waitForFunction(() => !document.querySelector('[role="dialog"]'), { timeout: 2000 });
  78. } finally {
  79. await page.close();
  80. }
  81. });
  82. test("IPE01 fit image uses normal cursor", async () => {
  83. const page = await browser.newPage({ viewport: { width: 1100, height: 844 } });
  84. try {
  85. await openPreview(page);
  86. const cursor = await page
  87. .locator('[role="dialog"] img')
  88. .evaluate((el) => getComputedStyle(el).cursor);
  89. assert.equal(cursor, "default");
  90. } finally {
  91. await page.close();
  92. }
  93. });
  94. test("IPE02 ordinary wheel zooms", async () => {
  95. const page = await browser.newPage({ viewport: { width: 1100, height: 844 } });
  96. try {
  97. await openPreview(page);
  98. await page.locator('[role="dialog"] img').hover();
  99. await page.mouse.wheel(0, -200);
  100. await page.waitForFunction(
  101. () =>
  102. !Array.from(document.querySelectorAll('[role="dialog"] span')).some(
  103. (e) => e.textContent === "100%",
  104. ),
  105. { timeout: 2000 },
  106. );
  107. } finally {
  108. await page.close();
  109. }
  110. });
  111. async function draw(page, tool = "pen", start = { x: 0.2, y: 0.2 }, end = { x: 0.6, y: 0.6 }) {
  112. await page.locator(`[data-image-preview-tool="${tool}"]`).click();
  113. const box = await page.locator("[data-image-preview-surface]").boundingBox();
  114. await page.mouse.move(box.x + box.width * start.x, box.y + box.height * start.y);
  115. await page.mouse.down();
  116. await page.mouse.move(box.x + box.width * end.x, box.y + box.height * end.y, { steps: 8 });
  117. await page.mouse.up();
  118. }
  119. for (const width of [390, 1100])
  120. for (const theme of ["light", "dark"])
  121. for (const locale of ["zh-CN", "en-US"]) {
  122. test(`IPE03/IPE06 editing ${width}/${theme}/${locale}`, async () => {
  123. const context = await browser.newContext({
  124. viewport: { width, height: 844 },
  125. hasTouch: width === 390,
  126. isMobile: width === 390,
  127. });
  128. const page = await context.newPage();
  129. const errors = [];
  130. page.on("pageerror", (error) => errors.push(String(error)));
  131. try {
  132. await openPreview(page, `theme=${theme}&locale=${locale}`);
  133. await draw(page);
  134. await draw(page, "rectangle", { x: 0.1, y: 0.5 }, { x: 0.4, y: 0.8 });
  135. await draw(page, "ellipse", { x: 0.6, y: 0.2 }, { x: 0.8, y: 0.4 });
  136. await draw(page, "arrow", { x: 0.5, y: 0.7 }, { x: 0.8, y: 0.8 });
  137. assert.equal(await page.locator("[data-annotation-id]").count(), 4);
  138. await page.locator('[data-image-preview-tool="text"]').click();
  139. const box = await page.locator("[data-image-preview-surface]").boundingBox();
  140. await page.mouse.click(box.x + box.width * 0.45, box.y + box.height * 0.1);
  141. await page
  142. .getByRole("textbox", { name: locale === "zh-CN" ? "标注文字" : "Annotation text" })
  143. .fill("标注 ABC");
  144. await page
  145. .getByRole("textbox", { name: locale === "zh-CN" ? "标注文字" : "Annotation text" })
  146. .press("ArrowLeft");
  147. await page
  148. .getByRole("textbox", { name: locale === "zh-CN" ? "标注文字" : "Annotation text" })
  149. .press("Enter");
  150. assert.equal(await page.locator("[data-annotation-id]").count(), 5);
  151. // 色值属于图片内容,不随深浅主题变化。
  152. await page.locator("input[type=color]").fill("#22c55e");
  153. await draw(page, "pen", { x: 0.1, y: 0.9 }, { x: 0.3, y: 0.9 });
  154. const green = page.locator('[data-annotation-id][stroke="#22c55e"]');
  155. assert.equal(await green.count(), 1);
  156. await page
  157. .getByRole("button", { name: locale === "zh-CN" ? "撤销" : "Undo", exact: true })
  158. .click();
  159. assert.equal(await green.count(), 0);
  160. await page
  161. .getByRole("button", { name: locale === "zh-CN" ? "重做" : "Redo", exact: true })
  162. .click();
  163. assert.equal(await green.count(), 1);
  164. await page.screenshot({ path: join(artifacts, `${width}-${theme}-${locale}.png`) });
  165. await page.locator("[data-image-preview-save]").click();
  166. await page.waitForFunction(() => window.savedFiles.length === 1);
  167. const saved = await page.evaluate(async () => {
  168. const f = window.savedFiles[0],
  169. image = await createImageBitmap(f),
  170. c = document.createElement("canvas");
  171. c.width = image.width;
  172. c.height = image.height;
  173. const ctx = c.getContext("2d");
  174. ctx.drawImage(image, 0, 0);
  175. image.close();
  176. return {
  177. name: f.name,
  178. type: f.type,
  179. width: c.width,
  180. height: c.height,
  181. green: [...ctx.getImageData(240, 720, 1, 1).data],
  182. original: [...ctx.getImageData(600, 500, 1, 1).data],
  183. };
  184. });
  185. assert.equal(saved.name, "drawing-edited.png");
  186. assert.equal(saved.type, "image/png");
  187. assert.equal(saved.width, 1200);
  188. assert.equal(saved.height, 800);
  189. assert.deepEqual(saved.green, [34, 197, 94, 255]);
  190. assert.deepEqual(saved.original, [135, 206, 235, 255]);
  191. await page.locator("[role=dialog]").waitFor({ state: "hidden" });
  192. assert.deepEqual(errors, []);
  193. } finally {
  194. await context.close();
  195. }
  196. });
  197. }
  198. test("IPE03 select moves a mark; eraser removes it; undo restores it", async () => {
  199. const page = await browser.newPage({ viewport: { width: 1100, height: 844 } });
  200. try {
  201. await openPreview(page);
  202. await draw(page, "rectangle");
  203. const before = await page.locator("[data-annotation-id] rect").getAttribute("x");
  204. await page.locator("[data-image-preview-tool=select]").click();
  205. const box = await page.locator("[data-image-preview-surface]").boundingBox();
  206. await page.mouse.move(box.x + box.width * 0.4, box.y + box.height * 0.2);
  207. await page.mouse.down();
  208. await page.mouse.move(box.x + box.width * 0.45, box.y + box.height * 0.3);
  209. await page.mouse.up();
  210. assert.notEqual(
  211. await page.locator("[data-annotation-id] rect").first().getAttribute("x"),
  212. before,
  213. );
  214. await page.locator("[data-image-preview-tool=eraser]").click();
  215. await page.mouse.click(box.x + box.width * 0.45, box.y + box.height * 0.3);
  216. assert.equal(await page.locator("[data-annotation-id]").count(), 0);
  217. await page.getByRole("button", { name: "撤销", exact: true }).click();
  218. assert.equal(await page.locator("[data-annotation-id]").count(), 1);
  219. } finally {
  220. await page.close();
  221. }
  222. });
  223. async function deferExport(page) {
  224. await page.evaluate(() => {
  225. const toBlob = HTMLCanvasElement.prototype.toBlob;
  226. HTMLCanvasElement.prototype.toBlob = function (...args) {
  227. window.finishExport = () => toBlob.apply(this, args);
  228. };
  229. });
  230. }
  231. for (const scenario of ["close", "scope", "double", "reject"])
  232. test(`IPE05 deferred save ${scenario}`, async () => {
  233. const page = await browser.newPage({ viewport: { width: 1100, height: 844 } });
  234. try {
  235. await openPreview(page);
  236. await draw(page);
  237. await deferExport(page);
  238. if (scenario === "reject") await page.evaluate(() => (window.rejectSave = true));
  239. await page.locator("[data-image-preview-save]").click();
  240. await page.waitForFunction(() => typeof window.finishExport === "function");
  241. if (scenario === "close") await page.keyboard.press("Escape");
  242. if (scenario === "scope") await page.evaluate(() => window.changeScope());
  243. if (scenario === "double")
  244. assert.equal(await page.locator("[data-image-preview-save]").isDisabled(), true);
  245. await page.evaluate(() => window.finishExport());
  246. if (scenario === "double") await page.waitForFunction(() => window.savedFiles.length === 1);
  247. else if (scenario !== "close")
  248. await page.getByText("图片保存失败,请重试", { exact: true }).waitFor();
  249. // 等待导出 callback 的结果可见,关闭分支另等解码/编码 promise 完成。
  250. if (scenario === "close")
  251. await page.waitForFunction(() => !document.querySelector("[role=dialog]"));
  252. assert.equal(
  253. await page.evaluate(() => window.savedFiles.length),
  254. scenario === "double" ? 1 : 0,
  255. );
  256. if (scenario === "scope" || scenario === "reject")
  257. assert.equal(await page.locator("[data-annotation-id]").count(), 1);
  258. } finally {
  259. await page.close();
  260. }
  261. });
  262. test("IPE02 anchored wheel, bounded drag and touch pinch", async () => {
  263. const context = await browser.newContext({
  264. viewport: { width: 1100, height: 844 },
  265. hasTouch: true,
  266. });
  267. const page = await context.newPage();
  268. try {
  269. await openPreview(page);
  270. const surface = page.locator("[data-image-preview-surface]");
  271. const initial = await surface.boundingBox();
  272. const anchor = { x: initial.x + initial.width * 0.65, y: initial.y + initial.height * 0.5 };
  273. await page.mouse.move(anchor.x, anchor.y);
  274. await page.mouse.wheel(0, -150);
  275. await page.waitForFunction(
  276. () =>
  277. document
  278. .querySelector("[data-image-preview-surface]")
  279. .style.transform.includes("scale(1.") &&
  280. getComputedStyle(document.querySelector("[data-image-preview-surface]")).cursor === "grab",
  281. );
  282. const zoomed = await surface.boundingBox();
  283. assert.ok(Math.abs((anchor.x - zoomed.x) / zoomed.width - 0.65) < 0.005);
  284. await page.mouse.move(550, 420);
  285. await page.mouse.down();
  286. await page.mouse.move(950, 600, { steps: 5 });
  287. await page.mouse.up();
  288. assert.equal(await page.locator("[role=dialog]").count(), 1);
  289. const box = await surface.boundingBox(),
  290. vp = await page.locator("[data-image-preview-viewport]").boundingBox();
  291. assert.ok(box.x <= vp.x + 1 && box.x + box.width >= vp.x + vp.width - 1);
  292. const cdp = await context.newCDPSession(page);
  293. await cdp.send("Input.dispatchTouchEvent", {
  294. type: "touchStart",
  295. touchPoints: [
  296. { x: 400, y: 400, id: 1 },
  297. { x: 600, y: 400, id: 2 },
  298. ],
  299. });
  300. await cdp.send("Input.dispatchTouchEvent", {
  301. type: "touchMove",
  302. touchPoints: [
  303. { x: 350, y: 400, id: 1 },
  304. { x: 650, y: 400, id: 2 },
  305. ],
  306. });
  307. await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
  308. await page.waitForFunction(
  309. (previous) =>
  310. document.querySelector("[data-image-preview-surface]").getBoundingClientRect().width >
  311. previous,
  312. box.width,
  313. );
  314. await page.setViewportSize({ width: 390, height: 844 });
  315. await page.screenshot({ path: join(artifacts, "touch-resize.png") });
  316. assert.equal(await page.locator("[role=dialog]").count(), 1);
  317. } finally {
  318. await context.close();
  319. }
  320. });
  321. test("IPE05 encoder failure keeps edits and re-enables save", async () => {
  322. const page = await browser.newPage({ viewport: { width: 1100, height: 844 } });
  323. try {
  324. await openPreview(page);
  325. await draw(page);
  326. await page.evaluate(
  327. () =>
  328. (HTMLCanvasElement.prototype.toBlob = function (callback) {
  329. callback(null);
  330. }),
  331. );
  332. await page.locator("[data-image-preview-save]").click();
  333. await page.getByText("图片保存失败,请重试", { exact: true }).waitFor();
  334. assert.equal(await page.locator("[data-image-preview-save]").isEnabled(), true);
  335. assert.equal(await page.locator("[data-annotation-id]").count(), 1);
  336. assert.equal(await page.evaluate(() => window.savedFiles.length), 0);
  337. } finally {
  338. await page.close();
  339. }
  340. });
  341. test("IPE gallery navigation remains clickable beside editing tools", async () => {
  342. const page = await browser.newPage({ viewport: { width: 1100, height: 844 } });
  343. try {
  344. await openPreview(page, "locale=zh-CN&multi=1");
  345. await page.getByRole("button", { name: "下一张图片", exact: true }).click({ timeout: 3000 });
  346. await page.waitForFunction(
  347. () => document.querySelector("[role=dialog] img")?.alt === "second.svg",
  348. );
  349. await page.getByRole("button", { name: "上一张图片", exact: true }).click();
  350. await page.waitForFunction(
  351. () => document.querySelector("[role=dialog] img")?.alt === "drawing.svg",
  352. );
  353. } finally {
  354. await page.close();
  355. }
  356. });
  357. test("IPE01 clicking disabled save does not dismiss the preview", async () => {
  358. const page = await browser.newPage({ viewport: { width: 1100, height: 844 } });
  359. try {
  360. await openPreview(page);
  361. const save = page.locator("[data-image-preview-save]");
  362. assert.equal(await save.isDisabled(), true);
  363. const box = await save.boundingBox();
  364. await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
  365. await page.locator('[role="dialog"]').evaluate(async (el) => {
  366. await Promise.all(el.getAnimations().map((animation) => animation.finished));
  367. });
  368. assert.equal(await page.locator('[role="dialog"][data-state="open"]').count(), 1);
  369. } finally {
  370. await page.close();
  371. }
  372. });