Layout.test.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /**
  2. * Tests for the Layout component.
  3. */
  4. import { describe, it, expect, beforeEach, vi } from 'vitest';
  5. import { waitFor } from '@testing-library/react';
  6. import { render } from '../utils';
  7. import { Layout } from '../../components/Layout';
  8. import { http, HttpResponse } from 'msw';
  9. import { server } from '../mocks/server';
  10. import { SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, SIDEBAR_ORDER_KEY } from '../../utils/sidebarLayout';
  11. describe('Layout', () => {
  12. beforeEach(() => {
  13. vi.mocked(localStorage.getItem).mockReset();
  14. vi.mocked(localStorage.setItem).mockReset();
  15. vi.mocked(localStorage.removeItem).mockReset();
  16. vi.mocked(localStorage.clear).mockReset();
  17. localStorage.clear();
  18. server.use(
  19. http.get('/api/v1/printers/', () => {
  20. return HttpResponse.json([
  21. { id: 1, name: 'X1 Carbon', model: 'X1C', enabled: true },
  22. ]);
  23. }),
  24. http.get('/api/v1/printers/:id/status', () => {
  25. return HttpResponse.json({
  26. connected: true,
  27. state: 'IDLE',
  28. });
  29. }),
  30. http.get('/api/v1/version', () => {
  31. return HttpResponse.json({ version: '0.1.6', build: 'test' });
  32. }),
  33. http.get('/api/v1/settings/', () => {
  34. return HttpResponse.json({
  35. check_updates: false,
  36. check_printer_firmware: false,
  37. auto_archive: true,
  38. });
  39. }),
  40. http.get('/api/v1/external-links/', () => {
  41. return HttpResponse.json([]);
  42. }),
  43. http.get('/api/v1/smart-plugs/', () => {
  44. return HttpResponse.json([]);
  45. }),
  46. http.get('/api/v1/support/debug-logging', () => {
  47. return HttpResponse.json({ enabled: false });
  48. }),
  49. http.get('/api/v1/queue/', () => {
  50. return HttpResponse.json([]);
  51. }),
  52. http.get('/api/v1/pending-uploads/count', () => {
  53. return HttpResponse.json({ count: 0 });
  54. }),
  55. http.get('/api/v1/updates/check', () => {
  56. return HttpResponse.json({ update_available: false });
  57. }),
  58. http.get('/api/v1/auth/status', () => {
  59. return HttpResponse.json({ auth_enabled: false, requires_setup: false });
  60. }),
  61. http.get('/api/v1/printers/developer-mode-warnings', () => {
  62. return HttpResponse.json([]);
  63. })
  64. );
  65. });
  66. describe('rendering', () => {
  67. it('renders the sidebar', async () => {
  68. render(<Layout />);
  69. // Layout renders as a flex container with sidebar
  70. await waitFor(() => {
  71. const sidebar = document.querySelector('aside');
  72. expect(sidebar).toBeInTheDocument();
  73. });
  74. });
  75. it('renders navigation links', async () => {
  76. render(<Layout />);
  77. await waitFor(() => {
  78. // Navigation links should be present
  79. const links = document.querySelectorAll('a');
  80. expect(links.length).toBeGreaterThan(0);
  81. });
  82. });
  83. });
  84. describe('navigation', () => {
  85. it('has navigation items', async () => {
  86. render(<Layout />);
  87. await waitFor(() => {
  88. // Should have multiple navigation links
  89. const navLinks = document.querySelectorAll('a[href]');
  90. expect(navLinks.length).toBeGreaterThan(0);
  91. });
  92. });
  93. it('includes settings link', async () => {
  94. render(<Layout />);
  95. await waitFor(() => {
  96. // Settings link should exist (route /settings)
  97. const settingsLink = document.querySelector('a[href="/settings"]');
  98. expect(settingsLink).toBeInTheDocument();
  99. });
  100. });
  101. it('hides system nav items stored in sidebar layout preferences', async () => {
  102. vi.mocked(localStorage.getItem).mockImplementation((key) => {
  103. if (key === SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY) return JSON.stringify(['printers']);
  104. return null;
  105. });
  106. render(<Layout />);
  107. await waitFor(() => {
  108. const sidebar = document.querySelector('aside');
  109. expect(sidebar).toBeInTheDocument();
  110. expect(sidebar?.querySelector('a[href="/inventory"]')).toBeInTheDocument();
  111. });
  112. expect(document.querySelector('aside a[href="/"]')).toBeNull();
  113. });
  114. it('applies admin default sidebar hidden state with the default order', async () => {
  115. const storage: Record<string, string> = {};
  116. vi.mocked(localStorage.getItem).mockImplementation((key) => storage[key] ?? null);
  117. vi.mocked(localStorage.setItem).mockImplementation((key, value) => {
  118. storage[key] = value;
  119. });
  120. server.use(
  121. http.get('/api/v1/settings/default-sidebar-order', () =>
  122. HttpResponse.json({
  123. default_sidebar_order: JSON.stringify({
  124. order: ['inventory', 'printers', 'settings'],
  125. hiddenSystemItemIds: ['printers'],
  126. }),
  127. }),
  128. ),
  129. );
  130. render(<Layout />);
  131. await waitFor(() => {
  132. const sidebar = document.querySelector('aside');
  133. expect(sidebar).toBeInTheDocument();
  134. expect(sidebar?.querySelector('a[href="/inventory"]')).toBeInTheDocument();
  135. });
  136. await waitFor(() => {
  137. expect(document.querySelector('aside a[href="/"]')).toBeNull();
  138. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_ORDER_KEY, JSON.stringify(['inventory', 'printers', 'settings']));
  139. expect(localStorage.setItem).toHaveBeenCalledWith(SIDEBAR_HIDDEN_SYSTEM_ITEMS_KEY, JSON.stringify(['printers']));
  140. });
  141. });
  142. });
  143. describe('finance nav item', () => {
  144. it('stays out of the sidebar while billing is off', async () => {
  145. // billing_enabled defaults to false and the Finance page has nothing to
  146. // show without it, so the entry must not be there at all.
  147. render(<Layout />);
  148. await waitFor(() => {
  149. expect(document.querySelector('aside a[href="/stats"]')).toBeInTheDocument();
  150. });
  151. expect(document.querySelector('aside a[href="/finance"]')).toBeNull();
  152. });
  153. it('appears between Statistics and Settings once billing is on', async () => {
  154. server.use(
  155. http.get('/api/v1/settings/', () =>
  156. HttpResponse.json({
  157. check_updates: false,
  158. check_printer_firmware: false,
  159. auto_archive: true,
  160. billing_enabled: true,
  161. }),
  162. ),
  163. );
  164. render(<Layout />);
  165. await waitFor(() => {
  166. expect(document.querySelector('aside a[href="/finance"]')).toBeInTheDocument();
  167. });
  168. const sidebar = document.querySelector('aside');
  169. const hrefs = Array.from(sidebar?.querySelectorAll('a[href]') ?? []).map((a) => a.getAttribute('href'));
  170. expect(hrefs.indexOf('/finance')).toBeGreaterThan(hrefs.indexOf('/stats'));
  171. expect(hrefs.indexOf('/finance')).toBeLessThan(hrefs.indexOf('/settings'));
  172. });
  173. });
  174. describe('version display', () => {
  175. it('shows version info', async () => {
  176. render(<Layout />);
  177. await waitFor(() => {
  178. // Version info is displayed in sidebar
  179. expect(document.body).toBeInTheDocument();
  180. });
  181. });
  182. });
  183. describe('theme toggle', () => {
  184. it('has theme toggle button', async () => {
  185. render(<Layout />);
  186. await waitFor(() => {
  187. // Theme toggle should be present
  188. const buttons = document.querySelectorAll('button');
  189. expect(buttons.length).toBeGreaterThan(0);
  190. });
  191. });
  192. it('cycles through dark → light → system → dark', async () => {
  193. localStorage.setItem('theme-mode', 'dark');
  194. render(<Layout />);
  195. await waitFor(() => {
  196. // In dark mode, title should say "Switch to light mode"
  197. const btn = document.querySelector('button[title="Switch to light mode"]');
  198. expect(btn).toBeInTheDocument();
  199. });
  200. // Click to go from dark → light
  201. const lightBtn = document.querySelector('button[title="Switch to light mode"]')!;
  202. lightBtn.click();
  203. await waitFor(() => {
  204. // In light mode, title should say "Switch to system mode"
  205. const btn = document.querySelector('button[title="Switch to system mode"]');
  206. expect(btn).toBeInTheDocument();
  207. });
  208. // Click to go from light → system
  209. const systemBtn = document.querySelector('button[title="Switch to system mode"]')!;
  210. systemBtn.click();
  211. await waitFor(() => {
  212. // In system mode, title should say "Switch to dark mode"
  213. const btn = document.querySelector('button[title="Switch to dark mode"]');
  214. expect(btn).toBeInTheDocument();
  215. });
  216. // Click to go from system → dark
  217. const darkBtn = document.querySelector('button[title="Switch to dark mode"]')!;
  218. darkBtn.click();
  219. await waitFor(() => {
  220. // Back to dark mode
  221. const btn = document.querySelector('button[title="Switch to light mode"]');
  222. expect(btn).toBeInTheDocument();
  223. });
  224. });
  225. });
  226. describe('plate detection alert modal', () => {
  227. it('shows modal when plate-not-empty event is dispatched', async () => {
  228. render(<Layout />);
  229. // Dispatch the plate-not-empty event
  230. window.dispatchEvent(
  231. new CustomEvent('plate-not-empty', {
  232. detail: {
  233. printer_id: 1,
  234. printer_name: 'Test Printer',
  235. message: 'Objects detected on build plate',
  236. },
  237. })
  238. );
  239. await waitFor(() => {
  240. // Modal should appear with "Print Paused!" text
  241. expect(document.body.textContent).toContain('Print Paused!');
  242. expect(document.body.textContent).toContain('Test Printer');
  243. });
  244. });
  245. it('closes modal when I Understand button is clicked', async () => {
  246. render(<Layout />);
  247. // Dispatch the plate-not-empty event
  248. window.dispatchEvent(
  249. new CustomEvent('plate-not-empty', {
  250. detail: {
  251. printer_id: 1,
  252. printer_name: 'Test Printer',
  253. message: 'Objects detected on build plate',
  254. },
  255. })
  256. );
  257. await waitFor(() => {
  258. expect(document.body.textContent).toContain('Print Paused!');
  259. });
  260. // Click the "I Understand" button
  261. const button = document.querySelector('button');
  262. if (button && button.textContent?.includes('I Understand')) {
  263. button.click();
  264. }
  265. // Find and click the "I Understand" button by searching all buttons
  266. const buttons = document.querySelectorAll('button');
  267. buttons.forEach((btn) => {
  268. if (btn.textContent?.includes('I Understand')) {
  269. btn.click();
  270. }
  271. });
  272. await waitFor(() => {
  273. // Modal should be closed
  274. expect(document.body.textContent).not.toContain('Print Paused!');
  275. });
  276. });
  277. });
  278. describe('developer mode warning banner', () => {
  279. it('shows warning banner when printers lack developer mode', async () => {
  280. server.use(
  281. http.get('/api/v1/printers/developer-mode-warnings', () => {
  282. return HttpResponse.json([
  283. { printer_id: 1, name: 'X1 Carbon' },
  284. ]);
  285. })
  286. );
  287. render(<Layout />);
  288. await waitFor(() => {
  289. expect(document.body.textContent).toContain('Developer LAN mode is not enabled on');
  290. expect(document.body.textContent).toContain('X1 Carbon');
  291. });
  292. });
  293. it('shows multiple printer names in warning banner', async () => {
  294. server.use(
  295. http.get('/api/v1/printers/developer-mode-warnings', () => {
  296. return HttpResponse.json([
  297. { printer_id: 1, name: 'X1 Carbon' },
  298. { printer_id: 2, name: 'P1S' },
  299. ]);
  300. })
  301. );
  302. render(<Layout />);
  303. await waitFor(() => {
  304. expect(document.body.textContent).toContain('X1 Carbon');
  305. expect(document.body.textContent).toContain('P1S');
  306. });
  307. });
  308. it('hides warning banner when no printers lack developer mode', async () => {
  309. // Default handler returns empty array
  310. render(<Layout />);
  311. await waitFor(() => {
  312. const sidebar = document.querySelector('aside');
  313. expect(sidebar).toBeInTheDocument();
  314. });
  315. // Banner should not be present
  316. expect(document.body.textContent).not.toContain('Developer LAN mode is not enabled on');
  317. });
  318. it('shows how to enable link in warning banner', async () => {
  319. server.use(
  320. http.get('/api/v1/printers/developer-mode-warnings', () => {
  321. return HttpResponse.json([
  322. { printer_id: 1, name: 'X1 Carbon' },
  323. ]);
  324. })
  325. );
  326. render(<Layout />);
  327. await waitFor(() => {
  328. expect(document.body.textContent).toContain('How to enable');
  329. const link = document.querySelector('a[href*="enable-developer-mode"]');
  330. expect(link).toBeInTheDocument();
  331. });
  332. });
  333. });
  334. describe('update banner suppression for HA addon', () => {
  335. // HA Supervisor surfaces its own update notification natively in the HA
  336. // UI, so the in-app banner would be duplicate noise that links to a page
  337. // that just says "update via HA". Suppress it for HA addon deployments.
  338. it('hides the update-available banner when running as an HA addon', async () => {
  339. server.use(
  340. http.get('/api/v1/updates/check', () => {
  341. return HttpResponse.json({
  342. update_available: true,
  343. current_version: '0.2.4',
  344. latest_version: '0.2.5',
  345. is_docker: true,
  346. is_ha_addon: true,
  347. update_method: 'ha_addon',
  348. });
  349. }),
  350. );
  351. render(<Layout />);
  352. await waitFor(() => {
  353. const sidebar = document.querySelector('aside');
  354. expect(sidebar).toBeInTheDocument();
  355. });
  356. expect(document.body.textContent).not.toContain('Update available');
  357. });
  358. it('still shows the update-available banner for plain Docker deployments', async () => {
  359. server.use(
  360. http.get('/api/v1/updates/check', () => {
  361. return HttpResponse.json({
  362. update_available: true,
  363. current_version: '0.2.4',
  364. latest_version: '0.2.5',
  365. is_docker: true,
  366. is_ha_addon: false,
  367. update_method: 'docker',
  368. });
  369. }),
  370. );
  371. render(<Layout />);
  372. await waitFor(() => {
  373. expect(document.body.textContent).toContain('0.2.5');
  374. });
  375. });
  376. });
  377. describe('MakerWorld sidebar permission gate (#1175)', () => {
  378. // The MakerWorld sidebar entry was visible to every authenticated user
  379. // regardless of group permissions because Layout's `navPermissions` map
  380. // had no entry for `makerworld`. Backend routes already gated on
  381. // `makerworld:view`, so users without the permission saw the entry,
  382. // clicked, and got 403'd by every API call inside the page. The fix
  383. // adds `makerworld: 'makerworld:view'` to the map so the entry is
  384. // hidden when the permission is absent — same shape as every other
  385. // sidebar entry.
  386. const enableAuthWithUser = (permissions: string[]) => {
  387. server.use(
  388. http.get('/api/v1/auth/status', () =>
  389. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  390. ),
  391. http.get('/api/v1/auth/me', () =>
  392. HttpResponse.json({
  393. id: 1,
  394. username: 'tester',
  395. role: 'user',
  396. is_active: true,
  397. is_admin: false,
  398. groups: [{ id: 2, name: 'Standard Users' }],
  399. permissions,
  400. created_at: '2026-01-01T00:00:00Z',
  401. }),
  402. ),
  403. );
  404. // AuthProvider needs a token in localStorage to fetch /auth/me; the
  405. // value isn't validated by the mocked server.
  406. window.localStorage.setItem('auth_token', 'test-token');
  407. };
  408. const findMakerWorldNavLink = () => {
  409. // Sidebar nav links use react-router's `to` prop, which renders as a
  410. // plain `<a href="/makerworld">`. Match on the href so the test isn't
  411. // coupled to whatever locale string is rendered.
  412. return document.querySelector('aside a[href="/makerworld"]');
  413. };
  414. it('hides the MakerWorld nav entry when the user lacks makerworld:view', async () => {
  415. // Standard user without the MakerWorld permission. Every other
  416. // permission they hold (library:read, etc.) is irrelevant here — the
  417. // gate is per-entry and the MakerWorld entry must not render.
  418. enableAuthWithUser(['library:read', 'archives:read', 'queue:read']);
  419. render(<Layout />);
  420. await waitFor(() => {
  421. // Wait for the auth resolution + sidebar render. Some other nav
  422. // entry (Files / Archives) confirms the sidebar finished mounting.
  423. const sidebar = document.querySelector('aside');
  424. expect(sidebar).toBeInTheDocument();
  425. expect(sidebar?.querySelector('a[href="/files"]')).toBeInTheDocument();
  426. });
  427. expect(findMakerWorldNavLink()).toBeNull();
  428. });
  429. it('shows the MakerWorld nav entry when the user has makerworld:view', async () => {
  430. enableAuthWithUser([
  431. 'library:read',
  432. 'archives:read',
  433. 'queue:read',
  434. 'makerworld:view',
  435. ]);
  436. render(<Layout />);
  437. await waitFor(() => {
  438. expect(findMakerWorldNavLink()).toBeInTheDocument();
  439. });
  440. });
  441. });
  442. describe('Sidebar gate accepts granular read tiers (#1755)', () => {
  443. // Default Operators group is seeded with `*:read_own` only — never the
  444. // legacy `*:read`. Previously the sidebar gate checked the legacy alone,
  445. // so Archives / Queue / Files were hidden from every non-admin even
  446. // though the underlying API endpoints accepted their requests. These
  447. // tests pin that the gate accepts ANY of the three tiers (legacy /
  448. // _own / _all) for the three resources that ship granular variants.
  449. const enableAuthWithUser = (permissions: string[]) => {
  450. server.use(
  451. http.get('/api/v1/auth/status', () =>
  452. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  453. ),
  454. http.get('/api/v1/auth/me', () =>
  455. HttpResponse.json({
  456. id: 1,
  457. username: 'tester',
  458. role: 'user',
  459. is_active: true,
  460. is_admin: false,
  461. groups: [{ id: 2, name: 'Operators' }],
  462. permissions,
  463. created_at: '2026-01-01T00:00:00Z',
  464. }),
  465. ),
  466. );
  467. window.localStorage.setItem('auth_token', 'test-token');
  468. };
  469. const sidebarLink = (href: string) =>
  470. document.querySelector(`aside a[href="${href}"]`);
  471. it('shows Files in the sidebar when the user only has library:read_own', async () => {
  472. enableAuthWithUser(['library:read_own']);
  473. render(<Layout />);
  474. await waitFor(() => {
  475. expect(document.querySelector('aside')).toBeInTheDocument();
  476. expect(sidebarLink('/files')).toBeInTheDocument();
  477. });
  478. });
  479. it('shows Files in the sidebar when the user only has library:read_all', async () => {
  480. enableAuthWithUser(['library:read_all']);
  481. render(<Layout />);
  482. await waitFor(() => {
  483. expect(sidebarLink('/files')).toBeInTheDocument();
  484. });
  485. });
  486. it('shows Archives in the sidebar when the user only has archives:read_own', async () => {
  487. enableAuthWithUser(['archives:read_own']);
  488. render(<Layout />);
  489. await waitFor(() => {
  490. expect(sidebarLink('/archives')).toBeInTheDocument();
  491. });
  492. });
  493. it('shows Queue in the sidebar when the user only has queue:read_own', async () => {
  494. enableAuthWithUser(['queue:read_own']);
  495. render(<Layout />);
  496. await waitFor(() => {
  497. expect(sidebarLink('/queue')).toBeInTheDocument();
  498. });
  499. });
  500. it('still hides Files when the user has none of the three read tiers', async () => {
  501. enableAuthWithUser(['printers:read']);
  502. render(<Layout />);
  503. await waitFor(() => {
  504. expect(document.querySelector('aside')).toBeInTheDocument();
  505. });
  506. expect(sidebarLink('/files')).toBeNull();
  507. expect(sidebarLink('/archives')).toBeNull();
  508. expect(sidebarLink('/queue')).toBeNull();
  509. });
  510. });
  511. });