Layout.test.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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('version display', () => {
  144. it('shows version info', async () => {
  145. render(<Layout />);
  146. await waitFor(() => {
  147. // Version info is displayed in sidebar
  148. expect(document.body).toBeInTheDocument();
  149. });
  150. });
  151. });
  152. describe('theme toggle', () => {
  153. it('has theme toggle button', async () => {
  154. render(<Layout />);
  155. await waitFor(() => {
  156. // Theme toggle should be present
  157. const buttons = document.querySelectorAll('button');
  158. expect(buttons.length).toBeGreaterThan(0);
  159. });
  160. });
  161. it('cycles through dark → light → system → dark', async () => {
  162. localStorage.setItem('theme-mode', 'dark');
  163. render(<Layout />);
  164. await waitFor(() => {
  165. // In dark mode, title should say "Switch to light mode"
  166. const btn = document.querySelector('button[title="Switch to light mode"]');
  167. expect(btn).toBeInTheDocument();
  168. });
  169. // Click to go from dark → light
  170. const lightBtn = document.querySelector('button[title="Switch to light mode"]')!;
  171. lightBtn.click();
  172. await waitFor(() => {
  173. // In light mode, title should say "Switch to system mode"
  174. const btn = document.querySelector('button[title="Switch to system mode"]');
  175. expect(btn).toBeInTheDocument();
  176. });
  177. // Click to go from light → system
  178. const systemBtn = document.querySelector('button[title="Switch to system mode"]')!;
  179. systemBtn.click();
  180. await waitFor(() => {
  181. // In system mode, title should say "Switch to dark mode"
  182. const btn = document.querySelector('button[title="Switch to dark mode"]');
  183. expect(btn).toBeInTheDocument();
  184. });
  185. // Click to go from system → dark
  186. const darkBtn = document.querySelector('button[title="Switch to dark mode"]')!;
  187. darkBtn.click();
  188. await waitFor(() => {
  189. // Back to dark mode
  190. const btn = document.querySelector('button[title="Switch to light mode"]');
  191. expect(btn).toBeInTheDocument();
  192. });
  193. });
  194. });
  195. describe('plate detection alert modal', () => {
  196. it('shows modal when plate-not-empty event is dispatched', async () => {
  197. render(<Layout />);
  198. // Dispatch the plate-not-empty event
  199. window.dispatchEvent(
  200. new CustomEvent('plate-not-empty', {
  201. detail: {
  202. printer_id: 1,
  203. printer_name: 'Test Printer',
  204. message: 'Objects detected on build plate',
  205. },
  206. })
  207. );
  208. await waitFor(() => {
  209. // Modal should appear with "Print Paused!" text
  210. expect(document.body.textContent).toContain('Print Paused!');
  211. expect(document.body.textContent).toContain('Test Printer');
  212. });
  213. });
  214. it('closes modal when I Understand button is clicked', async () => {
  215. render(<Layout />);
  216. // Dispatch the plate-not-empty event
  217. window.dispatchEvent(
  218. new CustomEvent('plate-not-empty', {
  219. detail: {
  220. printer_id: 1,
  221. printer_name: 'Test Printer',
  222. message: 'Objects detected on build plate',
  223. },
  224. })
  225. );
  226. await waitFor(() => {
  227. expect(document.body.textContent).toContain('Print Paused!');
  228. });
  229. // Click the "I Understand" button
  230. const button = document.querySelector('button');
  231. if (button && button.textContent?.includes('I Understand')) {
  232. button.click();
  233. }
  234. // Find and click the "I Understand" button by searching all buttons
  235. const buttons = document.querySelectorAll('button');
  236. buttons.forEach((btn) => {
  237. if (btn.textContent?.includes('I Understand')) {
  238. btn.click();
  239. }
  240. });
  241. await waitFor(() => {
  242. // Modal should be closed
  243. expect(document.body.textContent).not.toContain('Print Paused!');
  244. });
  245. });
  246. });
  247. describe('developer mode warning banner', () => {
  248. it('shows warning banner when printers lack developer mode', async () => {
  249. server.use(
  250. http.get('/api/v1/printers/developer-mode-warnings', () => {
  251. return HttpResponse.json([
  252. { printer_id: 1, name: 'X1 Carbon' },
  253. ]);
  254. })
  255. );
  256. render(<Layout />);
  257. await waitFor(() => {
  258. expect(document.body.textContent).toContain('Developer LAN mode is not enabled on');
  259. expect(document.body.textContent).toContain('X1 Carbon');
  260. });
  261. });
  262. it('shows multiple printer names in warning banner', async () => {
  263. server.use(
  264. http.get('/api/v1/printers/developer-mode-warnings', () => {
  265. return HttpResponse.json([
  266. { printer_id: 1, name: 'X1 Carbon' },
  267. { printer_id: 2, name: 'P1S' },
  268. ]);
  269. })
  270. );
  271. render(<Layout />);
  272. await waitFor(() => {
  273. expect(document.body.textContent).toContain('X1 Carbon');
  274. expect(document.body.textContent).toContain('P1S');
  275. });
  276. });
  277. it('hides warning banner when no printers lack developer mode', async () => {
  278. // Default handler returns empty array
  279. render(<Layout />);
  280. await waitFor(() => {
  281. const sidebar = document.querySelector('aside');
  282. expect(sidebar).toBeInTheDocument();
  283. });
  284. // Banner should not be present
  285. expect(document.body.textContent).not.toContain('Developer LAN mode is not enabled on');
  286. });
  287. it('shows how to enable link in warning banner', async () => {
  288. server.use(
  289. http.get('/api/v1/printers/developer-mode-warnings', () => {
  290. return HttpResponse.json([
  291. { printer_id: 1, name: 'X1 Carbon' },
  292. ]);
  293. })
  294. );
  295. render(<Layout />);
  296. await waitFor(() => {
  297. expect(document.body.textContent).toContain('How to enable');
  298. const link = document.querySelector('a[href*="enable-developer-mode"]');
  299. expect(link).toBeInTheDocument();
  300. });
  301. });
  302. });
  303. describe('update banner suppression for HA addon', () => {
  304. // HA Supervisor surfaces its own update notification natively in the HA
  305. // UI, so the in-app banner would be duplicate noise that links to a page
  306. // that just says "update via HA". Suppress it for HA addon deployments.
  307. it('hides the update-available banner when running as an HA addon', async () => {
  308. server.use(
  309. http.get('/api/v1/updates/check', () => {
  310. return HttpResponse.json({
  311. update_available: true,
  312. current_version: '0.2.4',
  313. latest_version: '0.2.5',
  314. is_docker: true,
  315. is_ha_addon: true,
  316. update_method: 'ha_addon',
  317. });
  318. }),
  319. );
  320. render(<Layout />);
  321. await waitFor(() => {
  322. const sidebar = document.querySelector('aside');
  323. expect(sidebar).toBeInTheDocument();
  324. });
  325. expect(document.body.textContent).not.toContain('Update available');
  326. });
  327. it('still shows the update-available banner for plain Docker deployments', async () => {
  328. server.use(
  329. http.get('/api/v1/updates/check', () => {
  330. return HttpResponse.json({
  331. update_available: true,
  332. current_version: '0.2.4',
  333. latest_version: '0.2.5',
  334. is_docker: true,
  335. is_ha_addon: false,
  336. update_method: 'docker',
  337. });
  338. }),
  339. );
  340. render(<Layout />);
  341. await waitFor(() => {
  342. expect(document.body.textContent).toContain('0.2.5');
  343. });
  344. });
  345. });
  346. describe('MakerWorld sidebar permission gate (#1175)', () => {
  347. // The MakerWorld sidebar entry was visible to every authenticated user
  348. // regardless of group permissions because Layout's `navPermissions` map
  349. // had no entry for `makerworld`. Backend routes already gated on
  350. // `makerworld:view`, so users without the permission saw the entry,
  351. // clicked, and got 403'd by every API call inside the page. The fix
  352. // adds `makerworld: 'makerworld:view'` to the map so the entry is
  353. // hidden when the permission is absent — same shape as every other
  354. // sidebar entry.
  355. const enableAuthWithUser = (permissions: string[]) => {
  356. server.use(
  357. http.get('/api/v1/auth/status', () =>
  358. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  359. ),
  360. http.get('/api/v1/auth/me', () =>
  361. HttpResponse.json({
  362. id: 1,
  363. username: 'tester',
  364. role: 'user',
  365. is_active: true,
  366. is_admin: false,
  367. groups: [{ id: 2, name: 'Standard Users' }],
  368. permissions,
  369. created_at: '2026-01-01T00:00:00Z',
  370. }),
  371. ),
  372. );
  373. // AuthProvider needs a token in localStorage to fetch /auth/me; the
  374. // value isn't validated by the mocked server.
  375. window.localStorage.setItem('auth_token', 'test-token');
  376. };
  377. const findMakerWorldNavLink = () => {
  378. // Sidebar nav links use react-router's `to` prop, which renders as a
  379. // plain `<a href="/makerworld">`. Match on the href so the test isn't
  380. // coupled to whatever locale string is rendered.
  381. return document.querySelector('aside a[href="/makerworld"]');
  382. };
  383. it('hides the MakerWorld nav entry when the user lacks makerworld:view', async () => {
  384. // Standard user without the MakerWorld permission. Every other
  385. // permission they hold (library:read, etc.) is irrelevant here — the
  386. // gate is per-entry and the MakerWorld entry must not render.
  387. enableAuthWithUser(['library:read', 'archives:read', 'queue:read']);
  388. render(<Layout />);
  389. await waitFor(() => {
  390. // Wait for the auth resolution + sidebar render. Some other nav
  391. // entry (Files / Archives) confirms the sidebar finished mounting.
  392. const sidebar = document.querySelector('aside');
  393. expect(sidebar).toBeInTheDocument();
  394. expect(sidebar?.querySelector('a[href="/files"]')).toBeInTheDocument();
  395. });
  396. expect(findMakerWorldNavLink()).toBeNull();
  397. });
  398. it('shows the MakerWorld nav entry when the user has makerworld:view', async () => {
  399. enableAuthWithUser([
  400. 'library:read',
  401. 'archives:read',
  402. 'queue:read',
  403. 'makerworld:view',
  404. ]);
  405. render(<Layout />);
  406. await waitFor(() => {
  407. expect(findMakerWorldNavLink()).toBeInTheDocument();
  408. });
  409. });
  410. });
  411. describe('Sidebar gate accepts granular read tiers (#1755)', () => {
  412. // Default Operators group is seeded with `*:read_own` only — never the
  413. // legacy `*:read`. Previously the sidebar gate checked the legacy alone,
  414. // so Archives / Queue / Files were hidden from every non-admin even
  415. // though the underlying API endpoints accepted their requests. These
  416. // tests pin that the gate accepts ANY of the three tiers (legacy /
  417. // _own / _all) for the three resources that ship granular variants.
  418. const enableAuthWithUser = (permissions: string[]) => {
  419. server.use(
  420. http.get('/api/v1/auth/status', () =>
  421. HttpResponse.json({ auth_enabled: true, requires_setup: false }),
  422. ),
  423. http.get('/api/v1/auth/me', () =>
  424. HttpResponse.json({
  425. id: 1,
  426. username: 'tester',
  427. role: 'user',
  428. is_active: true,
  429. is_admin: false,
  430. groups: [{ id: 2, name: 'Operators' }],
  431. permissions,
  432. created_at: '2026-01-01T00:00:00Z',
  433. }),
  434. ),
  435. );
  436. window.localStorage.setItem('auth_token', 'test-token');
  437. };
  438. const sidebarLink = (href: string) =>
  439. document.querySelector(`aside a[href="${href}"]`);
  440. it('shows Files in the sidebar when the user only has library:read_own', async () => {
  441. enableAuthWithUser(['library:read_own']);
  442. render(<Layout />);
  443. await waitFor(() => {
  444. expect(document.querySelector('aside')).toBeInTheDocument();
  445. expect(sidebarLink('/files')).toBeInTheDocument();
  446. });
  447. });
  448. it('shows Files in the sidebar when the user only has library:read_all', async () => {
  449. enableAuthWithUser(['library:read_all']);
  450. render(<Layout />);
  451. await waitFor(() => {
  452. expect(sidebarLink('/files')).toBeInTheDocument();
  453. });
  454. });
  455. it('shows Archives in the sidebar when the user only has archives:read_own', async () => {
  456. enableAuthWithUser(['archives:read_own']);
  457. render(<Layout />);
  458. await waitFor(() => {
  459. expect(sidebarLink('/archives')).toBeInTheDocument();
  460. });
  461. });
  462. it('shows Queue in the sidebar when the user only has queue:read_own', async () => {
  463. enableAuthWithUser(['queue:read_own']);
  464. render(<Layout />);
  465. await waitFor(() => {
  466. expect(sidebarLink('/queue')).toBeInTheDocument();
  467. });
  468. });
  469. it('still hides Files when the user has none of the three read tiers', async () => {
  470. enableAuthWithUser(['printers:read']);
  471. render(<Layout />);
  472. await waitFor(() => {
  473. expect(document.querySelector('aside')).toBeInTheDocument();
  474. });
  475. expect(sidebarLink('/files')).toBeNull();
  476. expect(sidebarLink('/archives')).toBeNull();
  477. expect(sidebarLink('/queue')).toBeNull();
  478. });
  479. });
  480. });