draft-greeting-layout.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  4. import { clearAppData } from "#e2e/helpers/desktop-app";
  5. import { clearRendererViewport, setRendererViewport } from "#e2e/helpers/renderer-viewport";
  6. const artifacts = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/draft-greeting");
  7. type Sample = { width: number; height: number; font: number; lineHeight: number; inputTop: number };
  8. type TraceWindow = Window & { __finishGreetingTrace?: () => Sample[] };
  9. describe("DGJ01 草稿标题适配不推动输入框回弹", () => {
  10. before(async () => {
  11. await prepareV4ConversationE2E({ skipProvider: true });
  12. await setRendererViewport(1500, 900);
  13. // 上午/中午的短问候语可能无法触发缩字;只调整 renderer 时区,保持真实时钟继续运行。
  14. const offset = 14 - new Date().getUTCHours();
  15. await setRendererTimezone(`Etc/GMT${offset >= 0 ? "-" : "+"}${Math.abs(offset)}`);
  16. await browser.execute(() => {
  17. (
  18. window as Window & { __testActions?: { setLocale(locale: string): void } }
  19. ).__testActions!.setLocale("en-US");
  20. });
  21. await frames();
  22. await mkdir(artifacts, { recursive: true });
  23. });
  24. after(async () => {
  25. await browser.execute(() => (window as TraceWindow).__finishGreetingTrace?.());
  26. await setRendererTimezone("");
  27. await clearRendererViewport();
  28. await clearAppData();
  29. });
  30. it("左右侧栏开关和拖动期间,中英文双主题均无临时换行", async function () {
  31. this.timeout(120000);
  32. for (const theme of ["zai-light", "zai-dark"]) {
  33. for (const locale of ["zh-CN", "en-US"]) {
  34. await browser.execute(
  35. (theme, locale) => {
  36. const actions = (
  37. window as Window & {
  38. __testActions?: { setTheme(value: string): void; setLocale(value: string): void };
  39. }
  40. ).__testActions!;
  41. actions.setTheme(theme);
  42. actions.setLocale(locale);
  43. },
  44. theme,
  45. locale,
  46. );
  47. await browser.waitUntil(() =>
  48. browser.execute(() => {
  49. const title = document.querySelector<HTMLElement>("[data-v4-draft-greeting]");
  50. const pane = title?.closest<HTMLElement>("[data-session-lifecycle]");
  51. return (
  52. title &&
  53. title.getBoundingClientRect().width > 0 &&
  54. document.fonts.status === "loaded" &&
  55. pane?.dataset.sessionLifecycle === "ready" &&
  56. pane.dataset.projectionSeq !== ""
  57. );
  58. }),
  59. );
  60. await frames();
  61. // 每种语言单独准备宽度;不能让英文继承中文的窄布局并把合法换行算成抖动。
  62. await setSidePaneOpen(true);
  63. await resizeGreeting(1.1);
  64. await setSidePaneOpen(false);
  65. await browser.execute(() => {
  66. const title = document.querySelector<HTMLElement>("[data-v4-draft-greeting]")!;
  67. const input = document.querySelector<HTMLElement>('[data-testid="v4-composer"]')!;
  68. const samples: Sample[] = [];
  69. // 注册顺序晚于真实组件:读取 ResizeObserver 完成字号适配后的本次绘制布局。
  70. const capture = () => {
  71. const rect = title.getBoundingClientRect(),
  72. style = getComputedStyle(title);
  73. samples.push({
  74. width: rect.width,
  75. height: rect.height,
  76. font: parseFloat(style.fontSize),
  77. lineHeight: parseFloat(style.lineHeight),
  78. inputTop: input.getBoundingClientRect().top,
  79. });
  80. };
  81. const observer = new ResizeObserver(capture);
  82. observer.observe(title);
  83. observer.observe(input);
  84. capture();
  85. (window as TraceWindow).__finishGreetingTrace = () => {
  86. observer.disconnect();
  87. capture();
  88. delete (window as TraceWindow).__finishGreetingTrace;
  89. return samples;
  90. };
  91. });
  92. await setSidePaneOpen(true);
  93. await resizeGreeting(0.85);
  94. for (let i = 0; i < 2; i++) {
  95. await browser.execute(() =>
  96. document
  97. .querySelector<HTMLElement>(
  98. 'button[aria-label="切换侧边栏"], button[aria-label="Toggle sidebar"]',
  99. )!
  100. .click(),
  101. );
  102. await waitForPanelMotion();
  103. }
  104. await frames();
  105. await browser.saveScreenshot(join(artifacts, `greeting-narrow-${theme}-${locale}.png`));
  106. await setSidePaneOpen(false);
  107. await setSidePaneOpen(true);
  108. await setSidePaneOpen(false);
  109. const samples = await browser.execute(() =>
  110. (window as TraceWindow).__finishGreetingTrace!(),
  111. );
  112. await writeFile(
  113. join(artifacts, `greeting-${theme}-${locale}.json`),
  114. JSON.stringify(samples, null, 2),
  115. );
  116. await browser.saveScreenshot(join(artifacts, `greeting-wide-${theme}-${locale}.png`));
  117. expect(samples.length).toBeGreaterThan(2);
  118. expect(samples.some((sample) => sample.font < 30)).toBe(true);
  119. expect(samples.every((sample) => sample.height <= sample.lineHeight + 1)).toBe(true);
  120. const movement =
  121. Math.max(...samples.map((sample) => sample.inputTop)) -
  122. Math.min(...samples.map((sample) => sample.inputTop));
  123. expect(movement).toBeLessThanOrEqual(13);
  124. expect(samples.at(-1)!.font).toBe(30);
  125. }
  126. }
  127. });
  128. });
  129. async function setRendererTimezone(timezoneId: string) {
  130. const url = await browser.getUrl();
  131. await browser.electron.execute(
  132. async (electron, url, timezoneId) => {
  133. const target = electron.BrowserWindow.getAllWindows().find(
  134. (window) => !window.isDestroyed() && window.webContents.getURL() === url,
  135. );
  136. if (!target) throw new Error("没有找到测试所属窗口");
  137. const debuggerApi = target.webContents.debugger;
  138. if (!debuggerApi.isAttached()) debuggerApi.attach("1.3");
  139. await debuggerApi.sendCommand("Emulation.setTimezoneOverride", { timezoneId });
  140. },
  141. url,
  142. timezoneId,
  143. );
  144. }
  145. async function setSidePaneOpen(open: boolean) {
  146. await browser.execute((open) => {
  147. const visible = document.querySelector("#browser")!.getBoundingClientRect().width > 1;
  148. if (visible === open) return;
  149. Array.from(document.querySelectorAll<HTMLElement>('[data-testid="side-pane-toggle"]'))
  150. .find((button) => button.getBoundingClientRect().width > 0)!
  151. .click();
  152. }, open);
  153. await browser.waitUntil(() =>
  154. browser.execute(
  155. (open) => document.querySelector("#browser")!.getBoundingClientRect().width > 1 === open,
  156. open,
  157. ),
  158. );
  159. await waitForPanelMotion();
  160. }
  161. function frames() {
  162. return browser.executeAsync((done) => {
  163. requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => done())));
  164. });
  165. }
  166. async function resizeGreeting(ratio: number) {
  167. const drag = await browser.execute((ratio) => {
  168. const title = document.querySelector<HTMLElement>("[data-v4-draft-greeting]")!;
  169. const range = document.createRange();
  170. range.selectNodeContents(title.querySelector('[aria-hidden="true"]')!);
  171. const natural = range.getBoundingClientRect().width;
  172. const content = title.closest("[data-v4-timeline-scroll]")!.firstElementChild!;
  173. const contentStyle = getComputedStyle(content);
  174. // 标题有 672px 上限;拖动距离必须基于整列可用宽度,否则宽屏下无法真正收窄标题。
  175. const availableWidth =
  176. content.getBoundingClientRect().width -
  177. parseFloat(contentStyle.paddingLeft) -
  178. parseFloat(contentStyle.paddingRight);
  179. const rect = document
  180. .querySelector("[data-workspace-side-pane-resize-handle]")!
  181. .getBoundingClientRect();
  182. return {
  183. x: Math.round(rect.x + rect.width / 2),
  184. y: Math.round(rect.y + rect.height / 2),
  185. delta: Math.round(natural * ratio + 32 - availableWidth),
  186. };
  187. }, ratio);
  188. await browser.performActions([
  189. {
  190. type: "pointer",
  191. id: "greeting-resize",
  192. parameters: { pointerType: "mouse" },
  193. actions: [
  194. { type: "pointerMove", duration: 0, x: drag.x, y: drag.y },
  195. { type: "pointerDown", button: 0 },
  196. { type: "pointerMove", duration: 300, x: drag.x + drag.delta, y: drag.y },
  197. { type: "pointerUp", button: 0 },
  198. ],
  199. },
  200. ]);
  201. await browser.releaseActions();
  202. await frames();
  203. }
  204. async function waitForPanelMotion() {
  205. await frames();
  206. await browser.waitUntil(() =>
  207. browser.execute(
  208. () =>
  209. !document
  210. .getAnimations()
  211. .some(
  212. (animation) =>
  213. animation instanceof CSSTransition &&
  214. /^(width|flex-grow)$/.test(animation.transitionProperty),
  215. ),
  216. ),
  217. );
  218. }