plugin-store-mode-order.test.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import assert from "node:assert/strict";
  2. import { after, before, test } from "node:test";
  3. import { mkdir } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { tmpdir } from "node:os";
  6. import { fileURLToPath } from "node:url";
  7. import { createServer } from "vite";
  8. import react from "@vitejs/plugin-react";
  9. import tailwindcss from "@tailwindcss/vite";
  10. import { chromium } from "playwright-core";
  11. const root = fileURLToPath(new URL("../../../../../../", import.meta.url));
  12. const entry = "/packages/ui/test/browser/manual-review/pending/plugin-store-mode-order.fixture.tsx";
  13. let server;
  14. let browser;
  15. let origin;
  16. before(async () => {
  17. server = await createServer({
  18. root,
  19. configFile: false,
  20. plugins: [
  21. react(),
  22. tailwindcss(),
  23. {
  24. name: "responsive-fixture",
  25. configureServer(vite) {
  26. vite.middlewares.use(async (req, res, next) => {
  27. if (!req.url?.startsWith("/fixture?")) return next();
  28. res.setHeader("Content-Type", "text/html");
  29. res.end(
  30. await vite.transformIndexHtml(
  31. req.url,
  32. `<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>`,
  33. ),
  34. );
  35. });
  36. },
  37. },
  38. ],
  39. resolve: { alias: { "@": `${root}packages/ui/src` } },
  40. optimizeDeps: { entries: [entry.slice(1)] },
  41. server: { host: "127.0.0.1", port: 0 },
  42. });
  43. await server.listen();
  44. origin = server.resolvedUrls.local[0];
  45. browser = await chromium.launch(
  46. process.env.CHROME_EXECUTABLE_PATH
  47. ? { executablePath: process.env.CHROME_EXECUTABLE_PATH }
  48. : { channel: "chrome" },
  49. );
  50. });
  51. after(async () => {
  52. await browser?.close();
  53. await server?.close();
  54. });
  55. const official = "zcode-plugins-official";
  56. const config = {
  57. code: {
  58. categoryOrder: ["legal", "developer-tools", "productivity"],
  59. pluginOrder: { productivity: [`p7@${official}`, `p6@${official}`] },
  60. },
  61. work: {
  62. categoryOrder: ["other", "legal", "productivity", "developer-tools"],
  63. pluginOrder: { productivity: [`p5@${official}`, `p4@${official}`] },
  64. },
  65. };
  66. const artifacts = join(tmpdir(), "zcode-plugin-mode-order");
  67. for (const [width, locale, theme] of [
  68. [1200, "en-US", "light"],
  69. [390, "zh-CN", "dark"],
  70. ]) {
  71. test(`PSO-01/04/06/07/09 ${width}/${locale}/${theme}`, async () => {
  72. const page = await browser.newPage({ viewport: { width, height: 900 } });
  73. const errors = [];
  74. page.on("pageerror", (error) => errors.push(error.message));
  75. let requests = 0;
  76. let release;
  77. let status = 200;
  78. let body = config;
  79. const gate = new Promise((resolve) => {
  80. release = resolve;
  81. });
  82. await page.route("**/order", async (route) => {
  83. requests += 1;
  84. if (requests === 1) await gate;
  85. await route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
  86. });
  87. const cards = (scope) =>
  88. scope
  89. .getByTestId("plugin-store-card")
  90. .evaluateAll((elements) =>
  91. elements.map((e) => e.getAttribute("data-plugin-id").split("@")[0]),
  92. );
  93. const productSection = () =>
  94. page
  95. .locator("section")
  96. .filter({ has: page.locator('[data-group-key="category:productivity"]') });
  97. try {
  98. await page.goto(`${origin}fixture?locale=${locale}&theme=${theme}`);
  99. await page.getByTestId("plugin-store-list").waitFor();
  100. // 配置尚未返回,默认分类已经可以展开和浏览。
  101. assert.deepEqual(await cards(productSection()), ["p0", "p1", "p2", "p3", "p4", "p5"]);
  102. release();
  103. await page.waitForFunction(() =>
  104. document
  105. .querySelector('[data-group-key="category:productivity"]')
  106. ?.closest("section")
  107. ?.querySelector("[data-plugin-id]")
  108. ?.getAttribute("data-plugin-id")
  109. ?.startsWith("p7@"),
  110. );
  111. assert.deepEqual(await cards(productSection()), ["p7", "p6", "p0", "p1", "p2", "p3"]);
  112. // 第一块是精选,其固定名单没有受排序配置影响。
  113. const sections = () =>
  114. page.locator("section").filter({ has: page.getByTestId("plugin-store-card") });
  115. assert.deepEqual(await cards(sections().nth(0)), ["p1", "p0"]);
  116. assert.deepEqual(await cards(sections().nth(1)), ["dev"]);
  117. await productSection().getByTestId("plugin-store-group-toggle").click();
  118. assert.deepEqual(await cards(productSection()), [
  119. "p7",
  120. "p6",
  121. "p0",
  122. "p1",
  123. "p2",
  124. "p3",
  125. "p4",
  126. "p5",
  127. ]);
  128. await page.getByTestId("work").click();
  129. assert.deepEqual(await cards(sections().nth(1)), ["other"]);
  130. assert.deepEqual(await cards(productSection()), [
  131. "p5",
  132. "p4",
  133. "p0",
  134. "p1",
  135. "p2",
  136. "p3",
  137. "p6",
  138. "p7",
  139. ]);
  140. assert.deepEqual(await cards(sections().nth(0)), ["p1", "p0"]);
  141. assert.equal(requests, 1);
  142. assert.equal(
  143. await page.evaluate(() => localStorage.getItem("zcode-interface-mode")),
  144. "general",
  145. );
  146. // 个人与全量搜索继续按各自原来的名称顺序。
  147. await page.getByTestId("plugin-store-segment-personal").click();
  148. assert.deepEqual(await cards(page), ["personal-a", "personal-b"]);
  149. await page.getByTestId("code").click();
  150. assert.deepEqual(await cards(page), ["personal-a", "personal-b"]);
  151. await page.getByTestId("plugin-store-search").fill("p");
  152. const searchOrder = await cards(page);
  153. await page.getByTestId("work").click();
  154. assert.deepEqual(await cards(page), searchOrder);
  155. await page.getByTestId("plugin-store-search").fill("");
  156. await page.getByTestId("plugin-store-segment-public").click();
  157. // 失败刷新保留现有投影,成功撤销则恢复默认顺序。
  158. status = 503;
  159. const failed = page.waitForResponse((response) => response.url().endsWith("/order"));
  160. await page.getByTestId("refresh").click();
  161. await failed;
  162. assert.deepEqual(await cards(sections().nth(1)), ["other"]);
  163. status = 200;
  164. body = null;
  165. await page.getByTestId("refresh").click();
  166. await page.waitForFunction(() =>
  167. document
  168. .querySelector('[data-group-key="category:productivity"]')
  169. ?.closest("section")
  170. ?.querySelector("[data-plugin-id]")
  171. ?.getAttribute("data-plugin-id")
  172. ?.startsWith("p0@"),
  173. );
  174. assert.deepEqual(await cards(sections().nth(1)), [
  175. "p0",
  176. "p1",
  177. "p2",
  178. "p3",
  179. "p4",
  180. "p5",
  181. "p6",
  182. "p7",
  183. ]);
  184. assert.equal(requests, 3);
  185. const categoryTitles = await page.locator("section h2").allTextContents();
  186. assert.equal(categoryTitles.includes(locale === "zh-CN" ? "指南" : "Guides"), false);
  187. assert.equal(categoryTitles.includes(locale === "zh-CN" ? "法律" : "Legal"), false);
  188. const legacyCategory = await page
  189. .locator(
  190. '[data-testid="plugin-store-card"][data-plugin-id="legacy-guide@zcode-plugins-official"]',
  191. )
  192. .evaluate((element) => element.closest("section").querySelector("h2").textContent);
  193. assert.equal(legacyCategory, locale === "zh-CN" ? "实用工具" : "Utilities");
  194. assert.equal(
  195. await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
  196. true,
  197. );
  198. assert.deepEqual(errors, []);
  199. await mkdir(artifacts, { recursive: true });
  200. await page.screenshot({
  201. path: join(artifacts, `${width}-${locale}-${theme}.png`),
  202. fullPage: true,
  203. });
  204. // 仅测试目录加入一条未来法律插件;当前真实目录仍没有法律插件。
  205. body = config;
  206. await page.goto(`${origin}fixture?locale=${locale}&theme=${theme}&legal=1`);
  207. const legalCard = page.locator(
  208. '[data-testid="plugin-store-card"][data-plugin-id="legal-example@zcode-plugins-official"]',
  209. );
  210. await legalCard.waitFor();
  211. assert.equal(
  212. await legalCard.evaluate(
  213. (element) => element.closest("section").querySelector("h2").textContent,
  214. ),
  215. locale === "zh-CN" ? "法律" : "Legal",
  216. );
  217. await page.waitForFunction(() => {
  218. const sections = Array.from(document.querySelectorAll("section")).filter((s) =>
  219. s.querySelector('[data-testid="plugin-store-card"]'),
  220. );
  221. return (
  222. sections[1]?.querySelector("[data-plugin-id]")?.getAttribute("data-plugin-id") ===
  223. "legal-example@zcode-plugins-official"
  224. );
  225. });
  226. assert.deepEqual(errors, []);
  227. // 退出市场的官方插件即使已安装、被精选或仍在旧目录中也不可见;个人同名插件保留。
  228. await page.goto(`${origin}fixture?locale=${locale}&theme=${theme}&retired=1`);
  229. await page.getByTestId("plugin-store-list").waitFor();
  230. const retired = page.locator(`[data-plugin-id="restore-legacy-sessions@${official}"]`);
  231. for (const mode of ["code", "work"]) {
  232. await page.getByTestId(mode).click();
  233. assert.equal(await retired.count(), 0);
  234. assert.equal(await page.getByTestId("plugin-store-installed-strip").count(), 0);
  235. await page.getByTestId("plugin-store-search").fill("restore-legacy-sessions");
  236. assert.equal(await retired.count(), 0);
  237. assert.equal(await page.getByTestId("plugin-store-card").count(), 1);
  238. assert.equal(
  239. await page.getByTestId("plugin-store-card").getAttribute("data-plugin-id"),
  240. "restore-legacy-sessions@personal",
  241. );
  242. await page.getByTestId("plugin-store-search").fill("");
  243. }
  244. await page.getByTestId("plugin-store-segment-personal").click();
  245. assert.equal(
  246. await page
  247. .locator(
  248. '[data-testid="plugin-store-card"][data-plugin-id="restore-legacy-sessions@personal"]',
  249. )
  250. .count(),
  251. 1,
  252. );
  253. assert.deepEqual(errors, []);
  254. } finally {
  255. release();
  256. await page.close();
  257. }
  258. });
  259. }
  260. for (const width of [1200, 390]) {
  261. for (const locale of ["en-US", "zh-CN"]) {
  262. for (const theme of ["light", "dark"]) {
  263. test(`PLM-MISSING-CONFIG ${width}/${locale}/${theme}`, async () => {
  264. const page = await browser.newPage({ viewport: { width, height: 900 } });
  265. const errors = [];
  266. page.on("pageerror", (error) => errors.push(error.message));
  267. try {
  268. await page.route("**/order", (route) => route.fulfill({ json: config }));
  269. await page.goto(`${origin}fixture?missingConfig=1&locale=${locale}&theme=${theme}`);
  270. const card = (name) =>
  271. page.locator(`[data-testid="plugin-store-card"][data-plugin-id="${name}@${official}"]`);
  272. await card("documents").waitFor();
  273. assert.equal(await card("document-skills").count(), 0);
  274. for (const name of ["documents", "pdf", "presentations", "spreadsheets", "image-search"])
  275. assert.equal(await card(name).count(), 1, name);
  276. assert.equal(
  277. await card("repairable")
  278. .getByRole("button", { name: locale === "zh-CN" ? "安装" : "Install", exact: true })
  279. .count(),
  280. 1,
  281. );
  282. const bundledIcons = [
  283. ["plugin-creator", "plugin-creator.png"],
  284. ["documents", "documents.png"],
  285. ["pdf", "pdf.png"],
  286. ["presentations", "presentations.png"],
  287. ["spreadsheets", "spreadsheets.png"],
  288. ["image-search", "image-search.png"],
  289. ];
  290. await Promise.all(bundledIcons.map(([name]) => card(name).locator("img").waitFor()));
  291. await page.waitForFunction(() => {
  292. const images = document.querySelectorAll(
  293. '[data-plugin-id$="@zcode-plugins-official"] img',
  294. );
  295. return [...images].every((image) => image.complete && image.naturalWidth > 0);
  296. });
  297. for (const [name, assetName] of bundledIcons)
  298. assert.match(
  299. await card(name).locator("img").getAttribute("src"),
  300. new RegExp(assetName),
  301. );
  302. await mkdir(artifacts, { recursive: true });
  303. await page.screenshot({
  304. path: join(artifacts, `missing-config-${width}-${locale}-${theme}.png`),
  305. });
  306. await page.getByRole("searchbox").fill("document-skills");
  307. assert.equal(await page.getByTestId("plugin-store-card").count(), 0);
  308. assert.deepEqual(errors, []);
  309. } finally {
  310. await page.close();
  311. }
  312. });
  313. }
  314. }
  315. }
  316. for (const width of [1200, 390]) {
  317. for (const locale of ["en-US", "zh-CN"]) {
  318. for (const theme of ["light", "dark"]) {
  319. test(`PLM-DOCUMENT-ORDER ${width}/${locale}/${theme}`, async () => {
  320. const page = await browser.newPage({ viewport: { width, height: 900 } });
  321. try {
  322. await page.route("**/order", (route) => route.fulfill({ json: null }));
  323. await page.goto(`${origin}fixture?documentOrder=1&locale=${locale}&theme=${theme}`);
  324. await page.getByTestId("plugin-store-installed-item").first().waitFor();
  325. const expected = ["pdf", "presentations", "spreadsheets", "documents"].map(
  326. (name) => `${name}@${official}`,
  327. );
  328. for (const mode of ["code", "work"]) {
  329. await page.getByTestId(mode).click();
  330. for (const testId of ["plugin-store-installed-item", "plugin-store-card"]) {
  331. const ids = await page
  332. .getByTestId(testId)
  333. .evaluateAll((elements) =>
  334. elements.slice(0, 4).map((element) => element.getAttribute("data-plugin-id")),
  335. );
  336. assert.deepEqual(ids, expected);
  337. }
  338. }
  339. await mkdir(artifacts, { recursive: true });
  340. await page.screenshot({
  341. path: join(artifacts, `document-order-${width}-${locale}-${theme}.png`),
  342. });
  343. } finally {
  344. await page.close();
  345. }
  346. });
  347. }
  348. }
  349. }