ProjectsPage.test.tsx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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 { eligibleParents } from '../../utils/projectTree';
  10. import { http, HttpResponse } from 'msw';
  11. import { server } from '../mocks/server';
  12. const mockProjects = [
  13. {
  14. id: 1,
  15. name: 'Functional Parts',
  16. description: 'Useful household items',
  17. color: '#00ae42',
  18. archive_count: 10,
  19. total_print_time_seconds: 36000,
  20. total_filament_grams: 500,
  21. created_at: '2024-01-01T00:00:00Z',
  22. updated_at: '2024-01-15T00:00:00Z',
  23. },
  24. {
  25. id: 2,
  26. name: 'Art Collection',
  27. description: 'Decorative prints',
  28. color: '#ff5500',
  29. archive_count: 5,
  30. total_print_time_seconds: 18000,
  31. total_filament_grams: 200,
  32. created_at: '2024-01-05T00:00:00Z',
  33. updated_at: '2024-01-10T00:00:00Z',
  34. },
  35. ];
  36. describe('ProjectsPage', () => {
  37. beforeEach(() => {
  38. server.use(
  39. http.get('/api/v1/projects/', () => {
  40. return HttpResponse.json(mockProjects);
  41. }),
  42. http.post('/api/v1/projects/', async ({ request }) => {
  43. const body = await request.json() as { name: string };
  44. return HttpResponse.json({ id: 3, name: body.name, color: '#00ae42', archive_count: 0 });
  45. }),
  46. http.delete('/api/v1/projects/:id', () => {
  47. return HttpResponse.json({ success: true });
  48. })
  49. );
  50. });
  51. describe('rendering', () => {
  52. it('renders the page title', async () => {
  53. render(<ProjectsPage />);
  54. await waitFor(() => {
  55. expect(screen.getByText('Projects')).toBeInTheDocument();
  56. });
  57. });
  58. it('shows project cards', async () => {
  59. render(<ProjectsPage />);
  60. await waitFor(() => {
  61. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  62. expect(screen.getByText('Art Collection')).toBeInTheDocument();
  63. });
  64. });
  65. it('shows project descriptions', async () => {
  66. render(<ProjectsPage />);
  67. await waitFor(() => {
  68. expect(screen.getByText('Useful household items')).toBeInTheDocument();
  69. expect(screen.getByText('Decorative prints')).toBeInTheDocument();
  70. });
  71. });
  72. });
  73. describe('project info', () => {
  74. it('shows archive count', async () => {
  75. render(<ProjectsPage />);
  76. await waitFor(() => {
  77. // Project cards should show archive counts
  78. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  79. });
  80. });
  81. it('shows project colors', async () => {
  82. render(<ProjectsPage />);
  83. await waitFor(() => {
  84. const functionalParts = screen.getByText('Functional Parts');
  85. expect(functionalParts).toBeInTheDocument();
  86. // Color is applied as style
  87. });
  88. });
  89. });
  90. describe('create project', () => {
  91. it('has new project button', async () => {
  92. render(<ProjectsPage />);
  93. await waitFor(() => {
  94. expect(screen.getByText('New Project')).toBeInTheDocument();
  95. });
  96. });
  97. it('opens create modal on click', async () => {
  98. const user = userEvent.setup();
  99. render(<ProjectsPage />);
  100. await waitFor(() => {
  101. expect(screen.getByText('New Project')).toBeInTheDocument();
  102. });
  103. await user.click(screen.getByText('New Project'));
  104. // Modal should open - look for modal content
  105. await waitFor(() => {
  106. // Modal may show "Create Project" or similar text
  107. const modalContent = screen.queryByText(/create/i) ||
  108. screen.queryByRole('dialog') ||
  109. screen.queryByText(/name/i);
  110. expect(modalContent).toBeTruthy();
  111. });
  112. });
  113. });
  114. describe('empty state', () => {
  115. it('shows empty state when no projects', async () => {
  116. server.use(
  117. http.get('/api/v1/projects/', () => {
  118. return HttpResponse.json([]);
  119. })
  120. );
  121. render(<ProjectsPage />);
  122. await waitFor(() => {
  123. // Either empty state message or the page title should be visible
  124. const emptyMsg = screen.queryByText(/no projects/i);
  125. const pageTitle = screen.queryByText('Projects');
  126. expect(emptyMsg || pageTitle).toBeTruthy();
  127. });
  128. });
  129. });
  130. // #1155 — URL link icon + cover image thumbnail on project cards.
  131. describe('URL link and cover image (#1155)', () => {
  132. it('renders an external-link icon next to the project name when URL is set', async () => {
  133. server.use(
  134. http.get('/api/v1/projects/', () =>
  135. HttpResponse.json([
  136. {
  137. ...mockProjects[0],
  138. url: 'https://makerworld.com/models/12345',
  139. cover_image_filename: null,
  140. },
  141. ])
  142. )
  143. );
  144. render(<ProjectsPage />);
  145. const link = await screen.findByLabelText(/Open project URL/i);
  146. expect(link).toBeInTheDocument();
  147. expect(link.getAttribute('href')).toBe('https://makerworld.com/models/12345');
  148. expect(link.getAttribute('target')).toBe('_blank');
  149. expect(link.getAttribute('rel')).toContain('noopener');
  150. });
  151. it('does not render the link icon when URL is not set', async () => {
  152. // Default fixture has no `url` field — verify the icon is absent.
  153. render(<ProjectsPage />);
  154. await waitFor(() => {
  155. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  156. });
  157. expect(screen.queryByLabelText(/Open project URL/i)).not.toBeInTheDocument();
  158. });
  159. it('clicking the URL link does not bubble to the card onClick', async () => {
  160. server.use(
  161. http.get('/api/v1/projects/', () =>
  162. HttpResponse.json([
  163. {
  164. ...mockProjects[0],
  165. url: 'https://example.com',
  166. cover_image_filename: null,
  167. },
  168. ])
  169. )
  170. );
  171. const user = userEvent.setup();
  172. render(<ProjectsPage />);
  173. const link = await screen.findByLabelText(/Open project URL/i);
  174. // Prevent the underlying anchor from triggering jsdom navigation noise
  175. // — we only need the propagation guard verified.
  176. link.addEventListener('click', (e) => e.preventDefault(), { once: true });
  177. await user.click(link);
  178. // No navigate / detail-page transition should have happened. Card root
  179. // is still rendered.
  180. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  181. });
  182. it('renders a cover image thumbnail when cover_image_filename is set', async () => {
  183. server.use(
  184. http.get('/api/v1/projects/', () =>
  185. HttpResponse.json([
  186. {
  187. ...mockProjects[0],
  188. url: null,
  189. cover_image_filename: 'cover_abc.png',
  190. },
  191. ])
  192. )
  193. );
  194. render(<ProjectsPage />);
  195. const img = await screen.findByAltText(/Project cover photo/i);
  196. expect(img).toBeInTheDocument();
  197. // Card thumbnail uses the GET endpoint URL, project.id is 1.
  198. expect(img.getAttribute('src')).toContain('/projects/1/cover-image');
  199. });
  200. it('renders the portal-mounted hover preview only while the thumbnail is hovered (#1155)', async () => {
  201. // The portal escapes the project card's ``overflow-hidden``, which
  202. // would otherwise clip a 384×384 popover anchored to a 40×40
  203. // thumbnail. Pin the contract end-to-end:
  204. // - no preview in the DOM by default (mouseenter not fired yet)
  205. // - mouseenter mounts a popover at document.body level (not
  206. // nested in the card subtree, which would re-introduce the
  207. // clipping bug)
  208. // - mouseleave unmounts it
  209. // - the popover ``<img>`` points at the same cover-image URL as
  210. // the small thumbnail (object-contain so portrait/landscape
  211. // MakerWorld photos aren't cropped)
  212. const { fireEvent } = await import('@testing-library/react');
  213. server.use(
  214. http.get('/api/v1/projects/', () =>
  215. HttpResponse.json([
  216. {
  217. ...mockProjects[0],
  218. url: null,
  219. cover_image_filename: 'cover_abc.png',
  220. },
  221. ])
  222. )
  223. );
  224. render(<ProjectsPage />);
  225. const thumb = await screen.findByAltText(/Project cover photo/i);
  226. // Default: no popover yet.
  227. expect(document.querySelectorAll('[aria-hidden="true"] img').length).toBe(0);
  228. // Hover: walk up to the wrapper div the component attaches its
  229. // mouseenter to. The portal mounts under document.body, NOT
  230. // nested in the card subtree.
  231. const wrapper = thumb.closest('[class*="flex-shrink-0"]') as HTMLElement;
  232. expect(wrapper).not.toBeNull();
  233. fireEvent.mouseEnter(wrapper);
  234. const previewImg = document.querySelector('[aria-hidden="true"] img') as HTMLImageElement | null;
  235. expect(previewImg).not.toBeNull();
  236. expect(previewImg!.getAttribute('src')).toContain('/projects/1/cover-image');
  237. expect(previewImg!.className).toContain('object-contain');
  238. // The portal mounts on document.body (or one of its direct
  239. // descendants), not inside the card — that's the whole point of
  240. // the portal, so a future refactor that drops the portal would
  241. // re-introduce the clipping regression.
  242. const popover = previewImg!.closest('[aria-hidden="true"]') as HTMLElement;
  243. expect(popover.closest('[class*="rounded-xl"]')).toBeNull();
  244. // Unmount on leave.
  245. fireEvent.mouseLeave(wrapper);
  246. expect(document.querySelectorAll('[aria-hidden="true"] img').length).toBe(0);
  247. });
  248. it('does not render a hover preview when there is no cover image', async () => {
  249. server.use(
  250. http.get('/api/v1/projects/', () =>
  251. HttpResponse.json([
  252. { ...mockProjects[0], url: null, cover_image_filename: null },
  253. ])
  254. )
  255. );
  256. render(<ProjectsPage />);
  257. await screen.findByText(mockProjects[0].name);
  258. expect(screen.queryByAltText(/Project cover photo/i)).toBeNull();
  259. // No aria-hidden img should ever appear because no thumbnail to
  260. // hover means the portal-mounting component never renders.
  261. expect(document.querySelectorAll('[aria-hidden="true"] img').length).toBe(0);
  262. });
  263. });
  264. describe('modal scrolls on short viewports (#1642)', () => {
  265. /**
  266. * Reporter on a Pi screen couldn't reach the Save button when editing a
  267. * project because the modal had no max-h / overflow. The structural fix
  268. * puts a max-h on the card, the form fields in a `flex-1 overflow-y-auto`
  269. * wrapper, and the Save/Cancel buttons in a `flex-shrink-0` sibling so
  270. * they're always visible regardless of scroll position.
  271. *
  272. * jsdom doesn't compute layout heights so we can't simulate the actual
  273. * overflow. We pin the structure instead: the scrollable wrapper exists,
  274. * the Save button is NOT a descendant of it, and the card has a max-h.
  275. * A future refactor that removes any of these would re-introduce the bug.
  276. */
  277. const editableProject = {
  278. id: 7,
  279. name: 'Spool holder',
  280. description: null,
  281. color: '#00ae42',
  282. url: null,
  283. cover_image_filename: null,
  284. archive_count: 0,
  285. total_print_time_seconds: 0,
  286. total_filament_grams: 0,
  287. target_plates_count: null,
  288. target_parts_count: null,
  289. tags: null,
  290. due_date: null,
  291. priority: null,
  292. budget: null,
  293. status: 'active' as const,
  294. created_at: '2024-01-01T00:00:00Z',
  295. updated_at: '2024-01-01T00:00:00Z',
  296. };
  297. it('renders the action footer outside the scrollable fields wrapper', () => {
  298. render(
  299. <ProjectModal
  300. project={editableProject}
  301. onClose={() => {}}
  302. onSave={() => {}}
  303. isLoading={false}
  304. currencySymbol="€"
  305. t={((k: string) => k) as never}
  306. />,
  307. );
  308. const saveButton = screen.getByRole('button', { name: 'common.save' });
  309. const scrollable = document.querySelector('.overflow-y-auto');
  310. expect(scrollable).not.toBeNull();
  311. // The save button must live OUTSIDE the scrollable region — otherwise
  312. // a long form pushes it below the fold on short viewports (#1642).
  313. expect(scrollable!.contains(saveButton)).toBe(false);
  314. });
  315. it('caps the modal card height so it cannot exceed the viewport', () => {
  316. render(
  317. <ProjectModal
  318. project={editableProject}
  319. onClose={() => {}}
  320. onSave={() => {}}
  321. isLoading={false}
  322. currencySymbol="€"
  323. t={((k: string) => k) as never}
  324. />,
  325. );
  326. // Card has max-h set so it never extends past the viewport — without
  327. // this, vertical-center alignment pushes the bottom of the modal
  328. // (including the action footer) off-screen.
  329. const card = document.querySelector('.max-h-\\[calc\\(100vh-2rem\\)\\]');
  330. expect(card).not.toBeNull();
  331. });
  332. });
  333. describe('edit dialog seeds itself from the list payload (#2536)', () => {
  334. /**
  335. * The same ProjectModal is opened from the projects list and from the
  336. * project detail page. The detail page hands it a full project; the list
  337. * hands it a list item. Reporter saw an empty tags field when editing from
  338. * the list, because the list payload didn't carry tags — and, unreported,
  339. * the dialog then submitted its default priority over the stored one.
  340. */
  341. const listItem = {
  342. id: 7,
  343. name: 'Spool holder',
  344. description: null,
  345. color: '#00ae42',
  346. status: 'active',
  347. target_count: null,
  348. target_parts_count: null,
  349. budget: null,
  350. tags: 'prototype,client-work',
  351. due_date: '2026-08-01T12:00:00Z',
  352. priority: 'high',
  353. created_at: '2024-01-01T00:00:00Z',
  354. archive_count: 0,
  355. total_items: 0,
  356. completed_count: 0,
  357. failed_count: 0,
  358. queue_count: 0,
  359. progress_percent: null,
  360. archives: [],
  361. url: null,
  362. cover_image_filename: null,
  363. };
  364. const renderModal = (onSave: (data: unknown) => void) =>
  365. render(
  366. <ProjectModal
  367. project={listItem}
  368. onClose={() => {}}
  369. onSave={onSave as never}
  370. isLoading={false}
  371. currencySymbol="€"
  372. t={((k: string) => k) as never}
  373. />,
  374. );
  375. const tagsInput = () => screen.getByPlaceholderText('projects.tagsPlaceholder') as HTMLInputElement;
  376. const dueDateInput = () => document.querySelector('input[type="date"]') as HTMLInputElement;
  377. const prioritySelect = () =>
  378. Array.from(document.querySelectorAll('select')).find((s) =>
  379. s.querySelector('option[value="urgent"]'),
  380. ) as HTMLSelectElement;
  381. it('prefills tags, due date and priority from a list item', () => {
  382. renderModal(() => {});
  383. expect(tagsInput().value).toBe('prototype,client-work');
  384. expect(dueDateInput().value).toBe('2026-08-01');
  385. expect(prioritySelect().value).toBe('high');
  386. });
  387. it('does not downgrade a stored priority when saving an untouched field', async () => {
  388. const user = userEvent.setup();
  389. const onSave = vi.fn();
  390. renderModal(onSave);
  391. await user.click(screen.getByRole('button', { name: 'common.save' }));
  392. // Before the fix the dialog fell back to its 'normal' default and sent
  393. // that, silently demoting a high/urgent project edited from the list.
  394. expect(onSave).toHaveBeenCalledWith(
  395. expect.objectContaining({ priority: 'high', tags: 'prototype,client-work' }),
  396. );
  397. });
  398. it('sends null when an existing tag list is cleared', async () => {
  399. const user = userEvent.setup();
  400. const onSave = vi.fn();
  401. renderModal(onSave);
  402. await user.clear(tagsInput());
  403. await user.click(screen.getByRole('button', { name: 'common.save' }));
  404. // undefined would drop the key from the PATCH body and the backend would
  405. // keep the old tags — the field has to be cleared explicitly.
  406. expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ tags: null }));
  407. });
  408. });
  409. describe('status tab badges (#2888)', () => {
  410. // Every tab is counted from the whole fleet, not from the page below it.
  411. const fleet = [
  412. { ...mockProjects[0], id: 1, status: 'active' },
  413. { ...mockProjects[1], id: 2, status: 'completed' },
  414. { ...mockProjects[1], id: 3, name: 'Last Year', status: 'archived' },
  415. { ...mockProjects[1], id: 4, name: 'Year Before', status: 'archived' },
  416. ];
  417. beforeEach(() => {
  418. // Stands in for the API's own status filter, so `projects` really does
  419. // hold one status at a time the way it does in the app.
  420. server.use(
  421. http.get('/api/v1/projects/', ({ request }) => {
  422. const status = new URL(request.url).searchParams.get('status');
  423. return HttpResponse.json(status ? fleet.filter((p) => p.status === status) : fleet);
  424. }),
  425. );
  426. });
  427. const badgeFor = (label: string) =>
  428. screen.getByRole('button', { name: new RegExp(`^${label}`) }).querySelector('span:last-child');
  429. it('counts the tabs the filter is hiding', async () => {
  430. // The page opens on Active, so before this every other tab counted zero
  431. // and dropped its badge -- the reporter's fleet of thirty finished
  432. // projects showed Completed bare next to "Active 5".
  433. render(<ProjectsPage />);
  434. await waitFor(() => expect(badgeFor('Active')).toHaveTextContent('1'));
  435. expect(badgeFor('Completed')).toHaveTextContent('1');
  436. expect(badgeFor('Archived')).toHaveTextContent('2');
  437. expect(badgeFor('All')).toHaveTextContent('4');
  438. });
  439. it('keeps the same counts after switching tabs', async () => {
  440. const user = userEvent.setup();
  441. render(<ProjectsPage />);
  442. await waitFor(() => expect(badgeFor('Archived')).toHaveTextContent('2'));
  443. await user.click(screen.getByRole('button', { name: /^Archived/ }));
  444. // Only the page below changes; the badges describe the fleet either way.
  445. await waitFor(() => expect(screen.getByText('Last Year')).toBeInTheDocument());
  446. expect(badgeFor('Active')).toHaveTextContent('1');
  447. expect(badgeFor('Completed')).toHaveTextContent('1');
  448. expect(badgeFor('All')).toHaveTextContent('4');
  449. });
  450. });
  451. describe('nesting projects under a master project (#1264)', () => {
  452. const listItem = (over: Record<string, unknown>) => ({
  453. id: 1,
  454. name: 'Airframe',
  455. description: null,
  456. color: '#00ae42',
  457. status: 'active',
  458. target_count: null,
  459. target_parts_count: null,
  460. target_sets: null,
  461. budget: null,
  462. tags: null,
  463. due_date: null,
  464. priority: 'normal',
  465. created_at: '2024-01-01T00:00:00Z',
  466. archive_count: 0,
  467. total_items: 0,
  468. completed_count: 0,
  469. failed_count: 0,
  470. queue_count: 0,
  471. progress_percent: null,
  472. parent_id: null,
  473. child_count: 0,
  474. archives: [],
  475. url: null,
  476. cover_image_filename: null,
  477. ...over,
  478. });
  479. describe('eligibleParents', () => {
  480. it('offers every other project when creating a new one', () => {
  481. const projects = [listItem({ id: 1 }), listItem({ id: 2, name: 'Wing' })];
  482. expect(eligibleParents(projects, undefined).map((p) => p.id)).toEqual([1, 2]);
  483. });
  484. it('never offers the project itself', () => {
  485. const projects = [listItem({ id: 1 }), listItem({ id: 2, name: 'Wing' })];
  486. expect(eligibleParents(projects, 1).map((p) => p.id)).toEqual([2]);
  487. });
  488. it('never offers a project already nested underneath', () => {
  489. // The API rejects a cycle, so offering one would only produce an error
  490. // the user can do nothing about.
  491. const projects = [
  492. listItem({ id: 1 }),
  493. listItem({ id: 2, name: 'Wing', parent_id: 1 }),
  494. listItem({ id: 3, name: 'Unrelated' }),
  495. ];
  496. expect(eligibleParents(projects, 1).map((p) => p.id)).toEqual([3]);
  497. });
  498. it('excludes a grandchild listed before its own parent', () => {
  499. // Reversion-proof for a single-pass version: the list arrives in update
  500. // order, so a grandchild can precede the parent that blocks it.
  501. const projects = [
  502. listItem({ id: 3, name: 'Spar', parent_id: 2 }),
  503. listItem({ id: 2, name: 'Wing', parent_id: 1 }),
  504. listItem({ id: 1 }),
  505. ];
  506. expect(eligibleParents(projects, 1)).toEqual([]);
  507. });
  508. });
  509. it('sends 0 to clear a parent, because null would read as omitted', async () => {
  510. const user = userEvent.setup();
  511. const onSave = vi.fn();
  512. server.use(http.get('/api/v1/projects/', () => HttpResponse.json([listItem({ id: 9, name: 'Other' })])));
  513. render(
  514. <ProjectModal
  515. project={listItem({ id: 1, parent_id: 9 })}
  516. onClose={() => {}}
  517. onSave={onSave as never}
  518. isLoading={false}
  519. currencySymbol="EUR"
  520. t={((k: string) => k) as never}
  521. />,
  522. );
  523. const parentSelect = () =>
  524. Array.from(document.querySelectorAll('select')).find((s) =>
  525. s.querySelector('option[value=""]'),
  526. ) as HTMLSelectElement;
  527. await waitFor(() => expect(parentSelect().value).toBe('9'));
  528. await user.selectOptions(parentSelect(), '');
  529. await user.click(screen.getByRole('button', { name: 'common.save' }));
  530. expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ parent_id: 0 }));
  531. });
  532. it('draws a sub-project inside its parent group, not loose in the grid', async () => {
  533. server.use(
  534. http.get('/api/v1/projects/', () =>
  535. HttpResponse.json([
  536. listItem({ id: 1, name: 'Airframe', child_count: 1 }),
  537. listItem({ id: 2, name: 'Wing', parent_id: 1 }),
  538. ]),
  539. ),
  540. );
  541. render(<ProjectsPage />);
  542. await waitFor(() => {
  543. expect(screen.getByText('Sub-projects of Airframe')).toBeInTheDocument();
  544. });
  545. // Two cards sitting columns apart cannot show that they belong together,
  546. // however they are captioned — the child has to be physically inside the
  547. // parent's group.
  548. const group = screen.getByText('Sub-projects of Airframe').closest('.col-span-full');
  549. expect(group).not.toBeNull();
  550. expect(group!.textContent).toContain('Wing');
  551. // And the caption is then redundant.
  552. expect(screen.queryByText('Part of Airframe')).not.toBeInTheDocument();
  553. });
  554. it('keeps a sub-project visible when the filter hides its parent', async () => {
  555. server.use(
  556. http.get('/api/v1/projects/', ({ request }) => {
  557. const status = new URL(request.url).searchParams.get('status');
  558. const all = [
  559. listItem({ id: 1, name: 'Airframe', status: 'completed', child_count: 1 }),
  560. listItem({ id: 2, name: 'Wing', parent_id: 1 }),
  561. ];
  562. return HttpResponse.json(status ? all.filter((p) => p.status === status) : all);
  563. }),
  564. );
  565. // The page opens on the Active filter, which already hides the completed
  566. // parent and leaves its active child with nowhere to nest.
  567. render(<ProjectsPage />);
  568. // Nothing to nest under, so it stays a top-level card — and then the
  569. // caption is the only thing that can say where it belongs.
  570. await waitFor(() => {
  571. expect(screen.getByText('Part of Airframe')).toBeInTheDocument();
  572. });
  573. expect(screen.queryByText('Sub-projects of Airframe')).not.toBeInTheDocument();
  574. });
  575. it('still shows every project when the data holds a parent cycle', async () => {
  576. // Grouping hides anything that has a visible parent, and a cycle has no
  577. // root — so A -> B -> A would take both projects off the page entirely.
  578. // A database written before the API refused a cycle can still hold one.
  579. server.use(
  580. http.get('/api/v1/projects/', () =>
  581. HttpResponse.json([
  582. listItem({ id: 1, name: 'Alpha', parent_id: 2 }),
  583. listItem({ id: 2, name: 'Beta', parent_id: 1 }),
  584. ]),
  585. ),
  586. );
  587. render(<ProjectsPage />);
  588. await waitFor(() => {
  589. expect(screen.getByText('Alpha')).toBeInTheDocument();
  590. });
  591. // Exactly once each: following the cycle round would redraw them.
  592. expect(screen.getAllByText('Alpha')).toHaveLength(1);
  593. expect(screen.getAllByText('Beta')).toHaveLength(1);
  594. });
  595. it('nests a grandchild under its own parent, not under the top of the tree', async () => {
  596. server.use(
  597. http.get('/api/v1/projects/', () =>
  598. HttpResponse.json([
  599. listItem({ id: 1, name: 'Airframe', child_count: 1 }),
  600. listItem({ id: 2, name: 'Wing', parent_id: 1, child_count: 1 }),
  601. listItem({ id: 3, name: 'Spar', parent_id: 2 }),
  602. ]),
  603. ),
  604. );
  605. render(<ProjectsPage />);
  606. await waitFor(() => {
  607. expect(screen.getByText('Sub-projects of Wing')).toBeInTheDocument();
  608. });
  609. const wingGroup = screen.getByText('Sub-projects of Wing').closest('.col-span-full');
  610. expect(wingGroup!.textContent).toContain('Spar');
  611. // Flattening every descendant onto the root would lose the depth.
  612. expect(wingGroup!.textContent).not.toContain('Airframe');
  613. });
  614. describe('folding sub-project groups away (#2991)', () => {
  615. // localStorage is globally mocked in setup.ts, so each test programs the
  616. // preference it wants explicitly.
  617. const getItemMock = localStorage.getItem as ReturnType<typeof vi.fn>;
  618. const setItemMock = localStorage.setItem as ReturnType<typeof vi.fn>;
  619. beforeEach(() => {
  620. getItemMock.mockReset();
  621. setItemMock.mockReset();
  622. });
  623. // The mock is module-global: an implementation left behind here would
  624. // silently collapse the groups of every later test.
  625. afterEach(() => {
  626. getItemMock.mockReset();
  627. setItemMock.mockReset();
  628. });
  629. const serveAirframe = () =>
  630. server.use(
  631. http.get('/api/v1/projects/', () =>
  632. HttpResponse.json([
  633. listItem({ id: 1, name: 'Airframe', child_count: 1 }),
  634. listItem({ id: 2, name: 'Wing', parent_id: 1 }),
  635. ]),
  636. ),
  637. );
  638. it('leaves groups open when no preference has been stored', async () => {
  639. getItemMock.mockReturnValue(null);
  640. serveAirframe();
  641. render(<ProjectsPage />);
  642. await waitFor(() => {
  643. expect(screen.getByText('Sub-projects of Airframe')).toBeInTheDocument();
  644. });
  645. // The page behaved this way before the toggle existed, and an upgrade
  646. // that hides half of somebody's projects is not a fix.
  647. expect(screen.getByText('Wing')).toBeInTheDocument();
  648. });
  649. it('opens with the groups shut when that is what was stored', async () => {
  650. getItemMock.mockImplementation((key: string) =>
  651. key === 'projects-collapse-subprojects' ? 'true' : null,
  652. );
  653. serveAirframe();
  654. render(<ProjectsPage />);
  655. await waitFor(() => {
  656. expect(screen.getByText('Sub-projects of Airframe')).toBeInTheDocument();
  657. });
  658. // The caption stays — it is the way back in, and it says what is behind
  659. // it. Only the cards go.
  660. expect(screen.queryByText('Wing')).not.toBeInTheDocument();
  661. });
  662. it('shuts one group from its own caption, leaving the others alone', async () => {
  663. getItemMock.mockReturnValue(null);
  664. server.use(
  665. http.get('/api/v1/projects/', () =>
  666. HttpResponse.json([
  667. listItem({ id: 1, name: 'Airframe', child_count: 1 }),
  668. listItem({ id: 2, name: 'Wing', parent_id: 1 }),
  669. listItem({ id: 3, name: 'Fuselage', child_count: 1 }),
  670. listItem({ id: 4, name: 'Bulkhead', parent_id: 3 }),
  671. ]),
  672. ),
  673. );
  674. const user = userEvent.setup();
  675. render(<ProjectsPage />);
  676. await waitFor(() => {
  677. expect(screen.getByText('Wing')).toBeInTheDocument();
  678. });
  679. await user.click(screen.getByRole('button', { name: /Sub-projects of Airframe/ }));
  680. await waitFor(() => {
  681. expect(screen.queryByText('Wing')).not.toBeInTheDocument();
  682. });
  683. expect(screen.getByText('Bulkhead')).toBeInTheDocument();
  684. // A per-group chevron is a passing choice, not a new default for the
  685. // whole page.
  686. expect(setItemMock).not.toHaveBeenCalledWith('projects-collapse-subprojects', 'true');
  687. });
  688. it('remembers the default the pill sets', async () => {
  689. getItemMock.mockReturnValue(null);
  690. const user = userEvent.setup();
  691. serveAirframe();
  692. render(<ProjectsPage />);
  693. await waitFor(() => {
  694. expect(screen.getByText('Wing')).toBeInTheDocument();
  695. });
  696. await user.click(screen.getByRole('button', { name: 'Collapse' }));
  697. await waitFor(() => {
  698. expect(screen.queryByText('Wing')).not.toBeInTheDocument();
  699. });
  700. expect(setItemMock).toHaveBeenCalledWith('projects-collapse-subprojects', 'true');
  701. });
  702. it('drops per-group choices when the default is flipped against them', async () => {
  703. getItemMock.mockReturnValue(null);
  704. const user = userEvent.setup();
  705. serveAirframe();
  706. render(<ProjectsPage />);
  707. await waitFor(() => {
  708. expect(screen.getByText('Wing')).toBeInTheDocument();
  709. });
  710. // Shut this one by hand, then ask for everything shut, then everything
  711. // open again. The hand-made choice was made against the old default,
  712. // and honouring it now would leave a group defying the pill the user
  713. // just pressed.
  714. await user.click(screen.getByRole('button', { name: /Sub-projects of Airframe/ }));
  715. await waitFor(() => {
  716. expect(screen.queryByText('Wing')).not.toBeInTheDocument();
  717. });
  718. await user.click(screen.getByRole('button', { name: 'Collapse' }));
  719. await user.click(screen.getByRole('button', { name: 'Collapse' }));
  720. await waitFor(() => {
  721. expect(screen.getByText('Wing')).toBeInTheDocument();
  722. });
  723. });
  724. it('counts what the chevron actually unfolds, not the card badge', async () => {
  725. // The API counts sub-projects across every status on purpose, so the
  726. // card badge says 2 while the Active filter leaves one child to show.
  727. // A caption repeating the badge would promise a card that is not there.
  728. getItemMock.mockImplementation((key: string) =>
  729. key === 'projects-collapse-subprojects' ? 'true' : null,
  730. );
  731. server.use(
  732. http.get('/api/v1/projects/', ({ request }) => {
  733. const status = new URL(request.url).searchParams.get('status');
  734. const all = [
  735. listItem({ id: 1, name: 'Airframe', child_count: 2 }),
  736. listItem({ id: 2, name: 'Wing', parent_id: 1 }),
  737. listItem({ id: 3, name: 'Tailplane', parent_id: 1, status: 'archived' }),
  738. ];
  739. return HttpResponse.json(status ? all.filter((p) => p.status === status) : all);
  740. }),
  741. );
  742. render(<ProjectsPage />);
  743. const caption = await screen.findByRole('button', { name: /Sub-projects of Airframe/ });
  744. expect(caption.textContent).toContain('1');
  745. expect(caption.textContent).not.toContain('2');
  746. });
  747. it('gives a shut group one grid cell instead of a whole row', async () => {
  748. // Folding a tree that still spends a full-width row per parent halves
  749. // the scrolling at best; the point is to get the page back.
  750. getItemMock.mockImplementation((key: string) =>
  751. key === 'projects-collapse-subprojects' ? 'true' : null,
  752. );
  753. serveAirframe();
  754. render(<ProjectsPage />);
  755. const caption = await screen.findByRole('button', { name: /Sub-projects of Airframe/ });
  756. expect(caption.closest('.col-span-full')).toBeNull();
  757. });
  758. it('offers no pill on a page where nothing is nested', async () => {
  759. getItemMock.mockReturnValue(null);
  760. render(<ProjectsPage />);
  761. await waitFor(() => {
  762. expect(screen.getByText('Functional Parts')).toBeInTheDocument();
  763. });
  764. // A control that cannot change anything is just one more thing to read.
  765. expect(screen.queryByRole('button', { name: 'Collapse' })).not.toBeInTheDocument();
  766. });
  767. });
  768. });
  769. });