conversation-session-message-file-link-line-jump.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. import { mkdir, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { TID_PREVIEW_PANE, TID_SIDE_PANE_TOGGLE } from "@zcode/shared/test-ids";
  4. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  5. import {
  6. prepareV4ConversationE2E,
  7. sendV4Prompt,
  8. waitForV4AssistantMessageContaining,
  9. waitForV4Pane,
  10. } from "#e2e/helpers/v4-conversation";
  11. // 规格:docs/ui/preview-pane.md「带行号的文件链接」;用例 MFL01(单行)、MFL02(区间与多段)。
  12. const MARKER = "E2E_MESSAGE_FILE_LINK_LINE_JUMP";
  13. const CASE_RELATIVE_ROOT = "file-link-line-jump-e2e";
  14. const CASE_ROOT = join(DEFAULT_WORKSPACE, CASE_RELATIVE_ROOT);
  15. const SAMPLE_FILE = join(CASE_ROOT, "sample.ts");
  16. const SAMPLE_LINE_COUNT = 150;
  17. const PREVIEW_PANE = `[data-testid="${TID_PREVIEW_PANE}"]`;
  18. const SIDE_PANE_TOGGLE = `[data-testid="${TID_SIDE_PANE_TOGGLE}"]`;
  19. /** 正文链接文案与 fixture 中的 Markdown 一一对应。 */
  20. const LINKS = {
  21. colonLine: "FLJ colon 42",
  22. hashLine: "FLJ hash 80",
  23. lineColumn: "FLJ line column 100",
  24. noLine: "FLJ no line",
  25. outOfRange: "FLJ out of range",
  26. } as const;
  27. /** MFL02 区间与多段链接文案,与 fixture 中的 Markdown 一一对应。 */
  28. const RANGE_LINKS = {
  29. colonRange: "FLR colon 30-35",
  30. hashRange: "FLR hash L30-L35",
  31. hashRangeShortEnd: "FLR hash L30-35",
  32. hashTallRange: "FLR hash L60-L140",
  33. colonPastEnd: "FLR colon 140-999",
  34. colonMultiLine: "FLR colon 30,40",
  35. colonMultiRange: "FLR colon 30-35,40-42",
  36. colonReversed: "FLR reversed 35-30",
  37. colonAllOutOfRange: "FLR out of range 9999-10000",
  38. } as const;
  39. /** 区间链接的滚动断言:整体放得下就居中;放不下时起始行置顶;贴近文件末尾时只要求整段可见。 */
  40. type RangeScrollExpectation = "center" | "top" | "visible";
  41. interface PreviewRangeState {
  42. ready: boolean;
  43. scrollTop: number;
  44. clientHeight: number;
  45. lineHeight: number;
  46. /** 期望区间首行顶部、末行底部相对滚动容器可视区顶部的偏移(像素);行不存在时为 null。 */
  47. spanTop: number | null;
  48. spanBottom: number | null;
  49. /** 代码行背景色与普通行不同的行号,即视觉上被高亮的行。 */
  50. highlightedLines: number[];
  51. /** 被高亮行的「代码背景色|行号背景色|行号文字色」去重集合;多段与单行高亮视觉一致时只有 1 种。 */
  52. highlightStyles: string[];
  53. codeViewerTabCount: number;
  54. errorText: string;
  55. }
  56. interface PreviewLineState {
  57. ready: boolean;
  58. scrollTop: number;
  59. clientHeight: number;
  60. /** 目标行中心相对滚动容器可视区中心的偏移(像素);目标行不存在时为 null。 */
  61. centerOffset: number | null;
  62. lineHeight: number;
  63. selectedLines: number[];
  64. codeViewerTabCount: number;
  65. errorText: string;
  66. }
  67. describe("消息正文带行号的文件链接定位", () => {
  68. after(async () => {
  69. await rm(CASE_ROOT, { recursive: true, force: true });
  70. await browser.electron.restoreAllMocks();
  71. await clearAppData();
  72. });
  73. it("MFL01: 三种行号写法居中高亮、同文件再次点击重新定位、重新挂载不回跳、无行号与超出行数停在开头", async () => {
  74. await prepareSampleFile();
  75. await prepareV4ConversationE2E();
  76. await sendV4Prompt(`${MARKER}: reply with file links to ${CASE_RELATIVE_ROOT}/sample.ts.`);
  77. await waitForV4AssistantMessageContaining(`${MARKER}_DONE`, 90_000);
  78. await waitForV4Pane(
  79. (pane) => !pane.canStop && pane.timelineText.includes(`${MARKER}_DONE`),
  80. "带行号文件链接夹具回复没有完成",
  81. 90_000,
  82. );
  83. // `a.ts:42`:首次打开预览,第 42 行居中并高亮。
  84. await clickBodyFileLink(LINKS.colonLine);
  85. await waitForFocusedLine(42);
  86. // 一次点击只定位一次:用户手动滚到文件末尾后,折叠再展开侧边面板让 CodeViewer 重新挂载,
  87. // 预览不能被拉回第 42 行;第 42 行的高亮保留。
  88. await scrollPreviewToBottom();
  89. await toggleSidePane();
  90. await waitForPreviewHidden();
  91. await toggleSidePane();
  92. await waitForNotRefocused(42);
  93. // 再点同一个 `:42` 链接:新的点击重新定位到第 42 行。
  94. await clickBodyFileLink(LINKS.colonLine);
  95. await waitForFocusedLine(42);
  96. // 预览已打开,点同文件 `#L80`:复用同一个 tab,并跳到新行。
  97. await clickBodyFileLink(LINKS.hashLine);
  98. await waitForFocusedLine(80);
  99. // `a.ts:100:5`:列号只解析不定位,效果与 `:100` 相同。
  100. await clickBodyFileLink(LINKS.lineColumn);
  101. await waitForFocusedLine(100);
  102. // 无行号:从开头显示,不高亮任何行。
  103. await clickBodyFileLink(LINKS.noLine);
  104. await waitForStaysAtTop("无行号链接");
  105. // 行号超出文件行数:先跳到一个有效行,确认超出行数时会回到开头而不是停在旧位置。
  106. await clickBodyFileLink(LINKS.colonLine);
  107. await waitForFocusedLine(42);
  108. await clickBodyFileLink(LINKS.outOfRange);
  109. await waitForStaysAtTop("超出行数链接");
  110. }).timeout(240_000);
  111. it("MFL02: 行号区间与多段整段高亮,放得下居中、放不下起始行置顶,超出部分截断或丢弃", async () => {
  112. await prepareSampleFile();
  113. await prepareV4ConversationE2E();
  114. await sendV4Prompt(`${MARKER}: reply with file links to ${CASE_RELATIVE_ROOT}/sample.ts.`);
  115. await waitForV4AssistantMessageContaining(`${MARKER}_DONE`, 90_000);
  116. await waitForV4Pane(
  117. (pane) => !pane.canStop && pane.timelineText.includes(`${MARKER}_DONE`),
  118. "带行号区间文件链接夹具回复没有完成",
  119. 90_000,
  120. );
  121. // `a.ts:30-35`:首次打开预览,第 30~35 行整段高亮并居中。
  122. await clickBodyFileLink(RANGE_LINKS.colonRange);
  123. await waitForFocusedRange(range(30, 35), 30, 35, "center");
  124. // `#L60-L140` 共 81 行,超过可视区:起始行 60 置顶。
  125. await clickBodyFileLink(RANGE_LINKS.hashTallRange);
  126. await waitForFocusedRange(range(60, 140), 60, 140, "top");
  127. // `#L30-L35` 与 `:30-35` 效果相同;中间隔一个不同位置,证明是重新定位而不是停在旧位置。
  128. await clickBodyFileLink(RANGE_LINKS.hashRange);
  129. await waitForFocusedRange(range(30, 35), 30, 35, "center");
  130. // `:140-999` 结束行超出文件末尾,截到最后一行 150。
  131. await clickBodyFileLink(RANGE_LINKS.colonPastEnd);
  132. await waitForFocusedRange(range(140, SAMPLE_LINE_COUNT), 140, SAMPLE_LINE_COUNT, "visible");
  133. // `#L30-35`(结束行不带 L)与 `#L30-L35` 相同。
  134. await clickBodyFileLink(RANGE_LINKS.hashRangeShortEnd);
  135. await waitForFocusedRange(range(30, 35), 30, 35, "center");
  136. // `:30,40` 多段:两行都高亮,从首段起始到末段结束整体居中。
  137. await clickBodyFileLink(RANGE_LINKS.colonMultiLine);
  138. await waitForFocusedRange([30, 40], 30, 40, "center");
  139. // `:30-35,40-42` 多段区间:所有段都高亮,段间的 36~39 不高亮。
  140. await clickBodyFileLink(RANGE_LINKS.colonMultiRange);
  141. await waitForFocusedRange([...range(30, 35), ...range(40, 42)], 30, 42, "center");
  142. // `:35-30` 结束行小于起始行:按单行起始行 35 处理。
  143. await clickBodyFileLink(RANGE_LINKS.colonReversed);
  144. await waitForFocusedRange([35], 35, 35, "center");
  145. // `:9999-10000` 所有段都超出行数:停在开头,不高亮,不报错。
  146. await clickBodyFileLink(RANGE_LINKS.colonAllOutOfRange);
  147. await waitForRangeStaysAtTop("全部段超出行数的区间链接");
  148. }).timeout(240_000);
  149. });
  150. function range(start: number, end: number): number[] {
  151. return Array.from({ length: end - start + 1 }, (_, index) => start + index);
  152. }
  153. async function prepareSampleFile() {
  154. await rm(CASE_ROOT, { recursive: true, force: true });
  155. await mkdir(CASE_ROOT, { recursive: true });
  156. const lines = Array.from(
  157. { length: SAMPLE_LINE_COUNT },
  158. (_, index) =>
  159. `export const flj_line_${String(index + 1).padStart(3, "0")} = "FLJ_LINE_${index + 1}";`,
  160. );
  161. await writeFile(SAMPLE_FILE, `${lines.join("\n")}\n`, "utf8");
  162. }
  163. async function clickBodyFileLink(label: string) {
  164. // 前一个用例的会话可能仍隐藏挂在 DOM 里,有同名链接;只点当前可见的那个。
  165. let link: WebdriverIO.Element | undefined;
  166. await browser.waitUntil(
  167. async () => {
  168. for (const candidate of await browser.$$(`button=${label}`)) {
  169. if (await candidate.isDisplayed()) {
  170. link = candidate;
  171. return true;
  172. }
  173. }
  174. return false;
  175. },
  176. { timeout: 30_000, timeoutMsg: `没有可见的文件链接 ${label}` },
  177. );
  178. if (!link) throw new Error(`没有可见的文件链接 ${label}`);
  179. await link.waitForStable();
  180. await link.waitForClickable();
  181. await link.click();
  182. }
  183. async function readPreviewLineState(targetLine: number | null): Promise<PreviewLineState> {
  184. return browser.execute(
  185. (paneSelector, line) => {
  186. const empty = {
  187. ready: false,
  188. scrollTop: -1,
  189. clientHeight: 0,
  190. centerOffset: null,
  191. lineHeight: 0,
  192. selectedLines: [] as number[],
  193. codeViewerTabCount: 0,
  194. errorText: "",
  195. };
  196. const codeViewerTabCount = document.querySelectorAll(
  197. '[data-side-pane-tab-id^="code-viewer:"]',
  198. ).length;
  199. const pane = document.querySelector<HTMLElement>(paneSelector);
  200. if (!pane) return { ...empty, codeViewerTabCount };
  201. const errorText =
  202. pane.querySelector<HTMLElement>(".text-destructive, .text-warning")?.textContent ?? "";
  203. const container = pane.querySelector<HTMLElement>("div[data-language]");
  204. if (!container) return { ...empty, codeViewerTabCount, errorText };
  205. // CodeViewer 的代码行渲染在 @pierre/diffs 的 Shadow DOM 中,与 findCodeViewerLineElement 同口径遍历。
  206. const roots: ParentNode[] = [container];
  207. for (let index = 0; index < roots.length; index += 1) {
  208. for (const element of roots[index]!.querySelectorAll<HTMLElement>("*")) {
  209. if (element.shadowRoot) roots.push(element.shadowRoot);
  210. }
  211. }
  212. const find = (selector: string) => {
  213. for (const root of roots) {
  214. const found = root.querySelector<HTMLElement>(selector);
  215. if (found) return found;
  216. }
  217. return null;
  218. };
  219. const selectedLines = new Set<number>();
  220. for (const root of roots) {
  221. for (const element of root.querySelectorAll<HTMLElement>(
  222. "[data-line][data-selected-line]",
  223. )) {
  224. selectedLines.add(Number(element.getAttribute("data-line")));
  225. }
  226. }
  227. const firstLine = find('[data-line="1"]');
  228. const target = line === null ? null : find(`[data-line="${line}"]`);
  229. const containerRect = container.getBoundingClientRect();
  230. const targetRect = target?.getBoundingClientRect();
  231. return {
  232. ready: Boolean(firstLine),
  233. scrollTop: container.scrollTop,
  234. clientHeight: container.clientHeight,
  235. centerOffset: targetRect
  236. ? targetRect.top +
  237. targetRect.height / 2 -
  238. (containerRect.top + container.clientHeight / 2)
  239. : null,
  240. lineHeight: targetRect?.height ?? firstLine?.getBoundingClientRect().height ?? 0,
  241. selectedLines: [...selectedLines].sort((left, right) => left - right),
  242. codeViewerTabCount,
  243. errorText: errorText.trim(),
  244. };
  245. },
  246. PREVIEW_PANE,
  247. targetLine,
  248. );
  249. }
  250. async function waitForFocusedLine(line: number) {
  251. let state: PreviewLineState | null = null;
  252. await browser
  253. .waitUntil(
  254. async () => {
  255. state = await readPreviewLineState(line);
  256. return (
  257. state.ready &&
  258. state.scrollTop > 0 &&
  259. state.centerOffset !== null &&
  260. // 目标行中心与可视区中心的偏差不超过两行高度,即「在可视区中部」。
  261. Math.abs(state.centerOffset) <= Math.max(state.lineHeight * 2, 24) &&
  262. state.selectedLines.length === 1 &&
  263. state.selectedLines[0] === line
  264. );
  265. },
  266. { timeout: 20_000, interval: 200 },
  267. )
  268. .catch(() => {
  269. throw new Error(`第 ${line} 行没有居中高亮: ${JSON.stringify(state)}`);
  270. });
  271. // 同一文件始终复用一个预览 tab。
  272. expect(state!.codeViewerTabCount).toBe(1);
  273. expect(state!.errorText).toBe("");
  274. }
  275. async function scrollPreviewToBottom() {
  276. await browser.execute((paneSelector) => {
  277. const container = document
  278. .querySelector<HTMLElement>(paneSelector)
  279. ?.querySelector<HTMLElement>("div[data-language]");
  280. if (!container) throw new Error("预览滚动容器不存在");
  281. container.scrollTop = container.scrollHeight;
  282. }, PREVIEW_PANE);
  283. let state: PreviewLineState | null = null;
  284. await browser
  285. .waitUntil(
  286. async () => {
  287. state = await readPreviewLineState(SAMPLE_LINE_COUNT);
  288. // 最后一行落在可视区下半部,即已滚到末尾。
  289. return (
  290. state.ready &&
  291. state.centerOffset !== null &&
  292. state.centerOffset > 0 &&
  293. state.centerOffset <= state.clientHeight / 2
  294. );
  295. },
  296. { timeout: 10_000, interval: 200 },
  297. )
  298. .catch(() => {
  299. throw new Error(`预览没有滚到文件末尾: ${JSON.stringify(state)}`);
  300. });
  301. }
  302. async function toggleSidePane() {
  303. let toggle: WebdriverIO.Element | undefined;
  304. await browser.waitUntil(
  305. async () => {
  306. for (const candidate of await browser.$$(SIDE_PANE_TOGGLE)) {
  307. if (await candidate.isDisplayed()) {
  308. toggle = candidate;
  309. return true;
  310. }
  311. }
  312. return false;
  313. },
  314. { timeout: 10_000, timeoutMsg: "没有可见的侧边面板开关" },
  315. );
  316. if (!toggle) throw new Error("没有可见的侧边面板开关");
  317. await toggle.click();
  318. }
  319. async function waitForPreviewHidden() {
  320. // 折叠后预览的代码内容卸载或不可见;再展开时 CodeViewer 会重新挂载。
  321. await browser.waitUntil(
  322. async () =>
  323. browser.execute((paneSelector) => {
  324. const container = document
  325. .querySelector<HTMLElement>(paneSelector)
  326. ?.querySelector<HTMLElement>("div[data-language]");
  327. return !container || container.getClientRects().length === 0;
  328. }, PREVIEW_PANE),
  329. { timeout: 10_000, interval: 200, timeoutMsg: "折叠侧边面板后预览仍可见" },
  330. );
  331. }
  332. async function waitForNotRefocused(line: number) {
  333. let state: PreviewLineState | null = null;
  334. let stableSamples = 0;
  335. // 连续多次采样:目标行都不在可视区中部,且高亮仍在,才算没有被旧的定位请求拉回。
  336. await browser
  337. .waitUntil(
  338. async () => {
  339. state = await readPreviewLineState(line);
  340. const refocused =
  341. state.centerOffset !== null &&
  342. Math.abs(state.centerOffset) <= Math.max(state.lineHeight * 2, 24);
  343. const ok =
  344. state.ready &&
  345. !refocused &&
  346. state.selectedLines.length === 1 &&
  347. state.selectedLines[0] === line;
  348. stableSamples = ok ? stableSamples + 1 : 0;
  349. return stableSamples >= 10;
  350. },
  351. { timeout: 20_000, interval: 150 },
  352. )
  353. .catch(() => {
  354. throw new Error(`重新挂载后预览被拉回第 ${line} 行或高亮丢失: ${JSON.stringify(state)}`);
  355. });
  356. expect(state!.codeViewerTabCount).toBe(1);
  357. expect(state!.errorText).toBe("");
  358. }
  359. async function waitForStaysAtTop(label: string) {
  360. let state: PreviewLineState | null = null;
  361. let stableSamples = 0;
  362. // 连续多次采样都停在开头才算通过,防止旧的定位请求在内容渲染后又把容器滚走。
  363. await browser
  364. .waitUntil(
  365. async () => {
  366. state = await readPreviewLineState(null);
  367. const atTop = state.ready && state.scrollTop === 0 && state.selectedLines.length === 0;
  368. stableSamples = atTop ? stableSamples + 1 : 0;
  369. return stableSamples >= 8;
  370. },
  371. { timeout: 20_000, interval: 150 },
  372. )
  373. .catch(() => {
  374. throw new Error(`${label} 没有停在开头: ${JSON.stringify(state)}`);
  375. });
  376. expect(state!.codeViewerTabCount).toBe(1);
  377. expect(state!.errorText).toBe("");
  378. }
  379. async function readPreviewRangeState(
  380. spanStartLine: number | null,
  381. spanEndLine: number | null,
  382. ): Promise<PreviewRangeState> {
  383. return browser.execute(
  384. (paneSelector, startLine, endLine) => {
  385. const empty = {
  386. ready: false,
  387. scrollTop: -1,
  388. clientHeight: 0,
  389. lineHeight: 0,
  390. spanTop: null,
  391. spanBottom: null,
  392. highlightedLines: [] as number[],
  393. highlightStyles: [] as string[],
  394. codeViewerTabCount: 0,
  395. errorText: "",
  396. };
  397. // 前一个用例的会话仍隐藏挂在 DOM 里,只看当前可见的预览面板和 tab。
  398. const isVisible = (element: Element) => element.getClientRects().length > 0;
  399. const codeViewerTabCount = [
  400. ...document.querySelectorAll('[data-side-pane-tab-id^="code-viewer:"]'),
  401. ].filter(isVisible).length;
  402. const pane = [...document.querySelectorAll<HTMLElement>(paneSelector)].find(isVisible);
  403. if (!pane) return { ...empty, codeViewerTabCount };
  404. const errorText =
  405. pane.querySelector<HTMLElement>(".text-destructive, .text-warning")?.textContent ?? "";
  406. const container = pane.querySelector<HTMLElement>("div[data-language]");
  407. if (!container) return { ...empty, codeViewerTabCount, errorText };
  408. const roots: ParentNode[] = [container];
  409. for (let index = 0; index < roots.length; index += 1) {
  410. for (const element of roots[index]!.querySelectorAll<HTMLElement>("*")) {
  411. if (element.shadowRoot) roots.push(element.shadowRoot);
  412. }
  413. }
  414. const codeLines = new Map<number, HTMLElement>();
  415. const gutterLines = new Map<number, HTMLElement>();
  416. for (const root of roots) {
  417. for (const element of root.querySelectorAll<HTMLElement>("[data-line]")) {
  418. if (element.hasAttribute("data-column-number")) continue;
  419. codeLines.set(Number(element.getAttribute("data-line")), element);
  420. }
  421. for (const element of root.querySelectorAll<HTMLElement>("[data-column-number]")) {
  422. gutterLines.set(Number(element.getAttribute("data-column-number")), element);
  423. }
  424. }
  425. // 高亮按真实视觉判定:以第 1 行(所有用例都不高亮它)的背景色为普通行基准,与之不同即为被高亮。
  426. // 这样同时覆盖 @pierre/diffs 原生选中行与额外段,并能检查两者视觉是否一致。
  427. const firstLineElement = codeLines.get(1);
  428. const normalBackground = firstLineElement
  429. ? getComputedStyle(firstLineElement).backgroundColor
  430. : "";
  431. const backgrounds = new Map<number, string>();
  432. for (const [line, element] of codeLines) {
  433. backgrounds.set(line, getComputedStyle(element).backgroundColor);
  434. }
  435. const highlightedLines: number[] = [];
  436. const highlightStyles = new Set<string>();
  437. for (const [line, background] of backgrounds) {
  438. if (background === normalBackground) continue;
  439. highlightedLines.push(line);
  440. const gutter = gutterLines.get(line);
  441. const gutterStyle = gutter ? getComputedStyle(gutter) : null;
  442. highlightStyles.add(
  443. `${background}|${gutterStyle?.backgroundColor ?? ""}|${gutterStyle?.color ?? ""}`,
  444. );
  445. }
  446. const containerTop = container.getBoundingClientRect().top;
  447. const startRect =
  448. startLine === null ? null : codeLines.get(startLine)?.getBoundingClientRect();
  449. const endRect = endLine === null ? null : codeLines.get(endLine)?.getBoundingClientRect();
  450. return {
  451. ready: codeLines.has(1),
  452. scrollTop: container.scrollTop,
  453. clientHeight: container.clientHeight,
  454. lineHeight: startRect?.height ?? codeLines.get(1)?.getBoundingClientRect().height ?? 0,
  455. spanTop: startRect ? startRect.top - containerTop : null,
  456. spanBottom: endRect ? endRect.bottom - containerTop : null,
  457. highlightedLines: highlightedLines.sort((left, right) => left - right),
  458. highlightStyles: [...highlightStyles],
  459. codeViewerTabCount,
  460. errorText: errorText.trim(),
  461. };
  462. },
  463. PREVIEW_PANE,
  464. spanStartLine,
  465. spanEndLine,
  466. );
  467. }
  468. function isRangeScrollSatisfied(state: PreviewRangeState, expectation: RangeScrollExpectation) {
  469. if (state.spanTop === null || state.spanBottom === null) return false;
  470. const tolerance = Math.max(state.lineHeight * 2, 24);
  471. if (expectation === "top") return Math.abs(state.spanTop) <= tolerance;
  472. if (expectation === "visible") {
  473. return state.spanTop >= 0 && state.spanBottom <= state.clientHeight + 1;
  474. }
  475. const spanCenter = (state.spanTop + state.spanBottom) / 2;
  476. return Math.abs(spanCenter - state.clientHeight / 2) <= tolerance;
  477. }
  478. async function waitForFocusedRange(
  479. expectedLines: number[],
  480. spanStartLine: number,
  481. spanEndLine: number,
  482. expectation: RangeScrollExpectation,
  483. ) {
  484. let state: PreviewRangeState | null = null;
  485. await browser
  486. .waitUntil(
  487. async () => {
  488. state = await readPreviewRangeState(spanStartLine, spanEndLine);
  489. return (
  490. state.ready &&
  491. state.scrollTop > 0 &&
  492. isRangeScrollSatisfied(state, expectation) &&
  493. // 区间内每一行都高亮,区间外没有;所有段的高亮视觉一致。
  494. state.highlightedLines.join(",") === expectedLines.join(",") &&
  495. state.highlightStyles.length === 1
  496. );
  497. },
  498. { timeout: 20_000, interval: 200 },
  499. )
  500. .catch(() => {
  501. throw new Error(
  502. `第 ${spanStartLine}~${spanEndLine} 行没有按 ${expectation} 定位并高亮 ${expectedLines.join(",")}: ${JSON.stringify(state)}`,
  503. );
  504. });
  505. expect(state!.codeViewerTabCount).toBe(1);
  506. expect(state!.errorText).toBe("");
  507. }
  508. async function waitForRangeStaysAtTop(label: string) {
  509. let state: PreviewRangeState | null = null;
  510. let stableSamples = 0;
  511. await browser
  512. .waitUntil(
  513. async () => {
  514. state = await readPreviewRangeState(null, null);
  515. const atTop = state.ready && state.scrollTop === 0 && state.highlightedLines.length === 0;
  516. stableSamples = atTop ? stableSamples + 1 : 0;
  517. return stableSamples >= 8;
  518. },
  519. { timeout: 20_000, interval: 150 },
  520. )
  521. .catch(() => {
  522. throw new Error(`${label} 没有停在开头: ${JSON.stringify(state)}`);
  523. });
  524. expect(state!.codeViewerTabCount).toBe(1);
  525. expect(state!.errorText).toBe("");
  526. }