ProjectsPage.test.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /**
  2. * Tests for the ProjectsPage component.
  3. */
  4. import { describe, it, expect, beforeEach, vi } from 'vitest';
  5. import { screen, waitFor } from '@testing-library/react';
  6. import userEvent from '@testing-library/user-event';
  7. import { render } from '../utils';
  8. import { ProjectsPage, ProjectModal } from '../../pages/ProjectsPage';
  9. import { http, HttpResponse } from 'msw';
  10. import { server } from '../mocks/server';
  11. const mockProjects = [
  12. {
  13. id: 1,
  14. name: 'Functional Parts',
  15. description: 'Useful household items',
  16. color: '#00ae42',
  17. archive_count: 10,
  18. total_print_time_seconds: 36000,
  19. total_filament_grams: 500,
  20. created_at: '2024-01-01T00:00:00Z',
  21. updated_at: '2024-01-15T00:00:00Z',
  22. },
  23. {
  24. id: 2,
  25. name: 'Art Collection',
  26. description: 'Decorative prints',
  27. color: '#ff5500',
  28. archive_count: 5,
  29. total_print_time_seconds: 18000,
  30. total_filament_grams: 200,
  31. created_at: '2024-01-05T00:00:00Z',
  32. updated_at: '2024-01-10T00:00:00Z',
  33. },
  34. ];
  35. describe('ProjectsPage', () => {
  36. beforeEach(() => {
  37. server.use(
  38. http.get('/api/v1/projects/', () => {
  39. return HttpResponse.json(mockProjects);
  40. }),
  41. http.post('/api/v1/projects/', async ({ request }) => {
  42. const body = await request.json() as { name: string };
  43. return HttpResponse.json({ id: 3, name: body.name, color: '#00ae42', archive_count: 0 });
  44. }),
  45. http.delete('/api/v1/projects/:id', () => {
  46. return HttpResponse.json({ success: true });
  47. })
  48. );
  49. });
  50. describe('rendering', () => {
  51. it('renders the page title', async () => {
  52. render(<ProjectsPage />);
  53. await waitFor(() => {
  54. expect(screen.getByText('Projects')).toBeInTheDocument();
  55. });
  56. });
  57. it('shows project cards', async () => {
  58. render(<ProjectsPage />);
  59. await waitFor(() => {
  60. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  61. expect(screen.getByText('Art Collection')).toBeInTheDocument();
  62. });
  63. });
  64. it('shows project descriptions', async () => {
  65. render(<ProjectsPage />);
  66. await waitFor(() => {
  67. expect(screen.getByText('Useful household items')).toBeInTheDocument();
  68. expect(screen.getByText('Decorative prints')).toBeInTheDocument();
  69. });
  70. });
  71. });
  72. describe('project info', () => {
  73. it('shows archive count', async () => {
  74. render(<ProjectsPage />);
  75. await waitFor(() => {
  76. // Project cards should show archive counts
  77. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  78. });
  79. });
  80. it('shows project colors', async () => {
  81. render(<ProjectsPage />);
  82. await waitFor(() => {
  83. const functionalParts = screen.getByText('Functional Parts');
  84. expect(functionalParts).toBeInTheDocument();
  85. // Color is applied as style
  86. });
  87. });
  88. });
  89. describe('create project', () => {
  90. it('has new project button', async () => {
  91. render(<ProjectsPage />);
  92. await waitFor(() => {
  93. expect(screen.getByText('New Project')).toBeInTheDocument();
  94. });
  95. });
  96. it('opens create modal on click', async () => {
  97. const user = userEvent.setup();
  98. render(<ProjectsPage />);
  99. await waitFor(() => {
  100. expect(screen.getByText('New Project')).toBeInTheDocument();
  101. });
  102. await user.click(screen.getByText('New Project'));
  103. // Modal should open - look for modal content
  104. await waitFor(() => {
  105. // Modal may show "Create Project" or similar text
  106. const modalContent = screen.queryByText(/create/i) ||
  107. screen.queryByRole('dialog') ||
  108. screen.queryByText(/name/i);
  109. expect(modalContent).toBeTruthy();
  110. });
  111. });
  112. });
  113. describe('empty state', () => {
  114. it('shows empty state when no projects', async () => {
  115. server.use(
  116. http.get('/api/v1/projects/', () => {
  117. return HttpResponse.json([]);
  118. })
  119. );
  120. render(<ProjectsPage />);
  121. await waitFor(() => {
  122. // Either empty state message or the page title should be visible
  123. const emptyMsg = screen.queryByText(/no projects/i);
  124. const pageTitle = screen.queryByText('Projects');
  125. expect(emptyMsg || pageTitle).toBeTruthy();
  126. });
  127. });
  128. });
  129. // #1155 — URL link icon + cover image thumbnail on project cards.
  130. describe('URL link and cover image (#1155)', () => {
  131. it('renders an external-link icon next to the project name when URL is set', async () => {
  132. server.use(
  133. http.get('/api/v1/projects/', () =>
  134. HttpResponse.json([
  135. {
  136. ...mockProjects[0],
  137. url: 'https://makerworld.com/models/12345',
  138. cover_image_filename: null,
  139. },
  140. ])
  141. )
  142. );
  143. render(<ProjectsPage />);
  144. const link = await screen.findByLabelText(/Open project URL/i);
  145. expect(link).toBeInTheDocument();
  146. expect(link.getAttribute('href')).toBe('https://makerworld.com/models/12345');
  147. expect(link.getAttribute('target')).toBe('_blank');
  148. expect(link.getAttribute('rel')).toContain('noopener');
  149. });
  150. it('does not render the link icon when URL is not set', async () => {
  151. // Default fixture has no `url` field — verify the icon is absent.
  152. render(<ProjectsPage />);
  153. await waitFor(() => {
  154. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  155. });
  156. expect(screen.queryByLabelText(/Open project URL/i)).not.toBeInTheDocument();
  157. });
  158. it('clicking the URL link does not bubble to the card onClick', async () => {
  159. server.use(
  160. http.get('/api/v1/projects/', () =>
  161. HttpResponse.json([
  162. {
  163. ...mockProjects[0],
  164. url: 'https://example.com',
  165. cover_image_filename: null,
  166. },
  167. ])
  168. )
  169. );
  170. const user = userEvent.setup();
  171. render(<ProjectsPage />);
  172. const link = await screen.findByLabelText(/Open project URL/i);
  173. // Prevent the underlying anchor from triggering jsdom navigation noise
  174. // — we only need the propagation guard verified.
  175. link.addEventListener('click', (e) => e.preventDefault(), { once: true });
  176. await user.click(link);
  177. // No navigate / detail-page transition should have happened. Card root
  178. // is still rendered.
  179. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  180. });
  181. it('renders a cover image thumbnail when cover_image_filename is set', async () => {
  182. server.use(
  183. http.get('/api/v1/projects/', () =>
  184. HttpResponse.json([
  185. {
  186. ...mockProjects[0],
  187. url: null,
  188. cover_image_filename: 'cover_abc.png',
  189. },
  190. ])
  191. )
  192. );
  193. render(<ProjectsPage />);
  194. const img = await screen.findByAltText(/Project cover photo/i);
  195. expect(img).toBeInTheDocument();
  196. // Card thumbnail uses the GET endpoint URL, project.id is 1.
  197. expect(img.getAttribute('src')).toContain('/projects/1/cover-image');
  198. });
  199. it('renders the portal-mounted hover preview only while the thumbnail is hovered (#1155)', async () => {
  200. // The portal escapes the project card's ``overflow-hidden``, which
  201. // would otherwise clip a 384×384 popover anchored to a 40×40
  202. // thumbnail. Pin the contract end-to-end:
  203. // - no preview in the DOM by default (mouseenter not fired yet)
  204. // - mouseenter mounts a popover at document.body level (not
  205. // nested in the card subtree, which would re-introduce the
  206. // clipping bug)
  207. // - mouseleave unmounts it
  208. // - the popover ``<img>`` points at the same cover-image URL as
  209. // the small thumbnail (object-contain so portrait/landscape
  210. // MakerWorld photos aren't cropped)
  211. const { fireEvent } = await import('@testing-library/react');
  212. server.use(
  213. http.get('/api/v1/projects/', () =>
  214. HttpResponse.json([
  215. {
  216. ...mockProjects[0],
  217. url: null,
  218. cover_image_filename: 'cover_abc.png',
  219. },
  220. ])
  221. )
  222. );
  223. render(<ProjectsPage />);
  224. const thumb = await screen.findByAltText(/Project cover photo/i);
  225. // Default: no popover yet.
  226. expect(document.querySelectorAll('[aria-hidden="true"] img').length).toBe(0);
  227. // Hover: walk up to the wrapper div the component attaches its
  228. // mouseenter to. The portal mounts under document.body, NOT
  229. // nested in the card subtree.
  230. const wrapper = thumb.closest('[class*="flex-shrink-0"]') as HTMLElement;
  231. expect(wrapper).not.toBeNull();
  232. fireEvent.mouseEnter(wrapper);
  233. const previewImg = document.querySelector('[aria-hidden="true"] img') as HTMLImageElement | null;
  234. expect(previewImg).not.toBeNull();
  235. expect(previewImg!.getAttribute('src')).toContain('/projects/1/cover-image');
  236. expect(previewImg!.className).toContain('object-contain');
  237. // The portal mounts on document.body (or one of its direct
  238. // descendants), not inside the card — that's the whole point of
  239. // the portal, so a future refactor that drops the portal would
  240. // re-introduce the clipping regression.
  241. const popover = previewImg!.closest('[aria-hidden="true"]') as HTMLElement;
  242. expect(popover.closest('[class*="rounded-xl"]')).toBeNull();
  243. // Unmount on leave.
  244. fireEvent.mouseLeave(wrapper);
  245. expect(document.querySelectorAll('[aria-hidden="true"] img').length).toBe(0);
  246. });
  247. it('does not render a hover preview when there is no cover image', async () => {
  248. server.use(
  249. http.get('/api/v1/projects/', () =>
  250. HttpResponse.json([
  251. { ...mockProjects[0], url: null, cover_image_filename: null },
  252. ])
  253. )
  254. );
  255. render(<ProjectsPage />);
  256. await screen.findByText(mockProjects[0].name);
  257. expect(screen.queryByAltText(/Project cover photo/i)).toBeNull();
  258. // No aria-hidden img should ever appear because no thumbnail to
  259. // hover means the portal-mounting component never renders.
  260. expect(document.querySelectorAll('[aria-hidden="true"] img').length).toBe(0);
  261. });
  262. });
  263. describe('modal scrolls on short viewports (#1642)', () => {
  264. /**
  265. * Reporter on a Pi screen couldn't reach the Save button when editing a
  266. * project because the modal had no max-h / overflow. The structural fix
  267. * puts a max-h on the card, the form fields in a `flex-1 overflow-y-auto`
  268. * wrapper, and the Save/Cancel buttons in a `flex-shrink-0` sibling so
  269. * they're always visible regardless of scroll position.
  270. *
  271. * jsdom doesn't compute layout heights so we can't simulate the actual
  272. * overflow. We pin the structure instead: the scrollable wrapper exists,
  273. * the Save button is NOT a descendant of it, and the card has a max-h.
  274. * A future refactor that removes any of these would re-introduce the bug.
  275. */
  276. const editableProject = {
  277. id: 7,
  278. name: 'Spool holder',
  279. description: null,
  280. color: '#00ae42',
  281. url: null,
  282. cover_image_filename: null,
  283. archive_count: 0,
  284. total_print_time_seconds: 0,
  285. total_filament_grams: 0,
  286. target_plates_count: null,
  287. target_parts_count: null,
  288. tags: null,
  289. due_date: null,
  290. priority: null,
  291. budget: null,
  292. status: 'active' as const,
  293. created_at: '2024-01-01T00:00:00Z',
  294. updated_at: '2024-01-01T00:00:00Z',
  295. };
  296. it('renders the action footer outside the scrollable fields wrapper', () => {
  297. render(
  298. <ProjectModal
  299. project={editableProject}
  300. onClose={() => {}}
  301. onSave={() => {}}
  302. isLoading={false}
  303. currencySymbol="€"
  304. t={((k: string) => k) as never}
  305. />,
  306. );
  307. const saveButton = screen.getByRole('button', { name: 'common.save' });
  308. const scrollable = document.querySelector('.overflow-y-auto');
  309. expect(scrollable).not.toBeNull();
  310. // The save button must live OUTSIDE the scrollable region — otherwise
  311. // a long form pushes it below the fold on short viewports (#1642).
  312. expect(scrollable!.contains(saveButton)).toBe(false);
  313. });
  314. it('caps the modal card height so it cannot exceed the viewport', () => {
  315. render(
  316. <ProjectModal
  317. project={editableProject}
  318. onClose={() => {}}
  319. onSave={() => {}}
  320. isLoading={false}
  321. currencySymbol="€"
  322. t={((k: string) => k) as never}
  323. />,
  324. );
  325. // Card has max-h set so it never extends past the viewport — without
  326. // this, vertical-center alignment pushes the bottom of the modal
  327. // (including the action footer) off-screen.
  328. const card = document.querySelector('.max-h-\\[calc\\(100vh-2rem\\)\\]');
  329. expect(card).not.toBeNull();
  330. });
  331. });
  332. describe('edit dialog seeds itself from the list payload (#2536)', () => {
  333. /**
  334. * The same ProjectModal is opened from the projects list and from the
  335. * project detail page. The detail page hands it a full project; the list
  336. * hands it a list item. Reporter saw an empty tags field when editing from
  337. * the list, because the list payload didn't carry tags — and, unreported,
  338. * the dialog then submitted its default priority over the stored one.
  339. */
  340. const listItem = {
  341. id: 7,
  342. name: 'Spool holder',
  343. description: null,
  344. color: '#00ae42',
  345. status: 'active',
  346. target_count: null,
  347. target_parts_count: null,
  348. budget: null,
  349. tags: 'prototype,client-work',
  350. due_date: '2026-08-01T12:00:00Z',
  351. priority: 'high',
  352. created_at: '2024-01-01T00:00:00Z',
  353. archive_count: 0,
  354. total_items: 0,
  355. completed_count: 0,
  356. failed_count: 0,
  357. queue_count: 0,
  358. progress_percent: null,
  359. archives: [],
  360. url: null,
  361. cover_image_filename: null,
  362. };
  363. const renderModal = (onSave: (data: unknown) => void) =>
  364. render(
  365. <ProjectModal
  366. project={listItem}
  367. onClose={() => {}}
  368. onSave={onSave as never}
  369. isLoading={false}
  370. currencySymbol="€"
  371. t={((k: string) => k) as never}
  372. />,
  373. );
  374. const tagsInput = () => screen.getByPlaceholderText('projects.tagsPlaceholder') as HTMLInputElement;
  375. const dueDateInput = () => document.querySelector('input[type="date"]') as HTMLInputElement;
  376. const prioritySelect = () =>
  377. Array.from(document.querySelectorAll('select')).find((s) =>
  378. s.querySelector('option[value="urgent"]'),
  379. ) as HTMLSelectElement;
  380. it('prefills tags, due date and priority from a list item', () => {
  381. renderModal(() => {});
  382. expect(tagsInput().value).toBe('prototype,client-work');
  383. expect(dueDateInput().value).toBe('2026-08-01');
  384. expect(prioritySelect().value).toBe('high');
  385. });
  386. it('does not downgrade a stored priority when saving an untouched field', async () => {
  387. const user = userEvent.setup();
  388. const onSave = vi.fn();
  389. renderModal(onSave);
  390. await user.click(screen.getByRole('button', { name: 'common.save' }));
  391. // Before the fix the dialog fell back to its 'normal' default and sent
  392. // that, silently demoting a high/urgent project edited from the list.
  393. expect(onSave).toHaveBeenCalledWith(
  394. expect.objectContaining({ priority: 'high', tags: 'prototype,client-work' }),
  395. );
  396. });
  397. it('sends null when an existing tag list is cleared', async () => {
  398. const user = userEvent.setup();
  399. const onSave = vi.fn();
  400. renderModal(onSave);
  401. await user.clear(tagsInput());
  402. await user.click(screen.getByRole('button', { name: 'common.save' }));
  403. // undefined would drop the key from the PATCH body and the backend would
  404. // keep the old tags — the field has to be cleared explicitly.
  405. expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ tags: null }));
  406. });
  407. });
  408. });