EmbeddedCameraViewer.test.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { StrictMode } from 'react';
  2. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
  3. import { act, fireEvent, screen, waitFor } from '@testing-library/react';
  4. import { http, HttpResponse } from 'msw';
  5. import { server } from '../mocks/server';
  6. import { render } from '../utils';
  7. import { EmbeddedCameraViewer } from '../../components/EmbeddedCameraViewer';
  8. // A detached img keeps its MJPEG connection open (measured in Chromium): the
  9. // backend stream, the chamber light it holds and the /camera/stop it blocks
  10. // stay until the browser closes. Every img the viewer drops has its src removed.
  11. async function settle() {
  12. await act(async () => {
  13. await Promise.resolve();
  14. });
  15. }
  16. function viewer() {
  17. return <EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />;
  18. }
  19. describe('EmbeddedCameraViewer stream lifetime', () => {
  20. beforeEach(() => {
  21. localStorage.clear();
  22. server.use(
  23. http.post('/api/v1/printers/:id/camera/stop', () => HttpResponse.json({ success: true })),
  24. http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })),
  25. );
  26. });
  27. afterEach(() => {
  28. vi.restoreAllMocks();
  29. });
  30. it('closes the stream when the viewer is minimized', async () => {
  31. render(viewer());
  32. await settle();
  33. const img = screen.getByAltText('Camera stream');
  34. expect(img.getAttribute('src')).toContain('/api/v1/printers/7/camera/stream');
  35. fireEvent.click(screen.getByTitle('Minimize'));
  36. await settle();
  37. expect(img.getAttribute('src')).toBeNull();
  38. });
  39. it('closes the current stream on close after the stream was restarted', async () => {
  40. const { unmount } = render(viewer());
  41. await settle();
  42. const first = screen.getByAltText('Camera stream');
  43. fireEvent.load(first);
  44. await waitFor(() => expect(screen.getByTitle('Refresh stream')).not.toBeDisabled());
  45. fireEvent.click(screen.getByTitle('Refresh stream'));
  46. await waitFor(() => expect(screen.getByAltText('Camera stream')).not.toBe(first));
  47. const current = screen.getByAltText('Camera stream');
  48. expect(current.getAttribute('src')).toContain('/camera/stream');
  49. unmount();
  50. await settle();
  51. expect(current.getAttribute('src')).toBeNull();
  52. });
  53. it('takes the error of a closed img for no stream failure', async () => {
  54. render(viewer());
  55. await settle();
  56. const img = screen.getByAltText('Camera stream');
  57. await act(async () => {
  58. img.setAttribute('src', ''); // what the reconnect and restart code does
  59. img.dispatchEvent(new Event('error'));
  60. });
  61. expect(screen.queryByText(/Reconnecting in/)).toBeNull();
  62. });
  63. it('stops its own stream by the viewer id it opened it with', async () => {
  64. const fetchMock = vi.spyOn(global, 'fetch');
  65. const { unmount } = render(viewer());
  66. await settle();
  67. const id = new URL((screen.getByAltText('Camera stream') as HTMLImageElement).src).searchParams.get('viewer');
  68. expect(id).toMatch(/^[A-Za-z0-9_-]{1,64}$/);
  69. unmount();
  70. const stop = fetchMock.mock.calls.map(([url]) => String(url)).find((url) => url.includes('/camera/stop'));
  71. expect(new URL(stop!, 'http://x').searchParams.get('viewer')).toBe(id);
  72. });
  73. it('names itself on the stop its Refresh sends', async () => {
  74. const fetchMock = vi.spyOn(global, 'fetch');
  75. render(viewer());
  76. await settle();
  77. const img = screen.getByAltText('Camera stream');
  78. const id = new URL((img as HTMLImageElement).src).searchParams.get('viewer');
  79. fireEvent.load(img);
  80. await waitFor(() => expect(screen.getByTitle('Refresh stream')).not.toBeDisabled());
  81. fireEvent.click(screen.getByTitle('Refresh stream'));
  82. const stop = fetchMock.mock.calls.map(([url]) => String(url)).find((url) => url.includes('/camera/stop'));
  83. expect(new URL(stop!, 'http://x').searchParams.get('viewer')).toBe(id);
  84. // Refresh reopens the stream 100 ms later: let that happen inside the test,
  85. // not after its environment is gone.
  86. await waitFor(() => expect(screen.getByAltText('Camera stream')).not.toBe(img));
  87. });
  88. it('keeps its stream under StrictMode', async () => {
  89. render(<StrictMode>{viewer()}</StrictMode>);
  90. await settle();
  91. expect(screen.getByAltText('Camera stream').getAttribute('src')).toContain('/api/v1/printers/7/camera/stream');
  92. });
  93. });
  94. // A sideways camera was laid out at the window's unswapped size and then
  95. // turned: cut off in a wide window, boxed in by black bars in a tall one (#3362).
  96. describe('EmbeddedCameraViewer with a camera turned sideways', () => {
  97. function sizeVideoArea(width: number, height: number) {
  98. const isVideoArea = (el: HTMLElement) => el.querySelector(':scope > img[alt="Camera stream"]') !== null;
  99. vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function (this: HTMLElement) {
  100. return isVideoArea(this) ? width : 0;
  101. });
  102. vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(function (this: HTMLElement) {
  103. return isVideoArea(this) ? height : 0;
  104. });
  105. }
  106. beforeEach(() => {
  107. localStorage.clear();
  108. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  109. });
  110. afterEach(() => {
  111. vi.restoreAllMocks();
  112. });
  113. it.each([
  114. [270, 400, 260, { maxWidth: '260px', maxHeight: '400px' }],
  115. [90, 260, 400, { maxWidth: '400px', maxHeight: '260px' }],
  116. ])('fits a camera turned %i degrees into a %ix%i window', async (rotation, width, height, expected) => {
  117. sizeVideoArea(width, height);
  118. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ id: 7, name: 'A1 Mini', camera_rotation: rotation })));
  119. render(viewer());
  120. const img = await screen.findByAltText('Camera stream');
  121. await waitFor(() => expect(img.style.transform).toContain(`rotate(${rotation}deg)`));
  122. await waitFor(() => expect(img).toHaveStyle(expected));
  123. });
  124. it('leaves an upright camera alone', async () => {
  125. sizeVideoArea(400, 260);
  126. server.use(http.get('/api/v1/printers/:id', () => HttpResponse.json({ id: 7, name: 'A1 Mini', camera_rotation: 180 })));
  127. render(viewer());
  128. const img = await screen.findByAltText('Camera stream');
  129. await waitFor(() => expect(img.style.transform).toContain('rotate(180deg)'));
  130. expect(img.style.maxWidth).toBe('');
  131. expect(img.style.maxHeight).toBe('');
  132. });
  133. });
  134. describe('EmbeddedCameraViewer pop-out (#2737)', () => {
  135. beforeEach(() => {
  136. server.use(
  137. http.post('/api/v1/printers/:id/camera/stop', () => HttpResponse.json({ success: true })),
  138. http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })),
  139. );
  140. });
  141. afterEach(() => {
  142. vi.restoreAllMocks();
  143. });
  144. it('opens the camera window and closes the overlay', async () => {
  145. const open = vi.spyOn(window, 'open').mockReturnValue({} as Window);
  146. const onClose = vi.fn();
  147. render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={onClose} />);
  148. await settle();
  149. fireEvent.click(screen.getByRole('button', { name: 'Open in its own window' }));
  150. expect(open).toHaveBeenCalledWith('/camera/7', 'camera-7', expect.any(String));
  151. expect(onClose).toHaveBeenCalledOnce();
  152. });
  153. it('keeps the overlay when a popup blocker stopped the window', async () => {
  154. vi.spyOn(window, 'open').mockReturnValue(null);
  155. const onClose = vi.fn();
  156. render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={onClose} />);
  157. await settle();
  158. fireEvent.click(screen.getByRole('button', { name: 'Open in its own window' }));
  159. expect(onClose).not.toHaveBeenCalled();
  160. });
  161. });
  162. describe('EmbeddedCameraViewer first position', () => {
  163. const originalWidth = window.innerWidth;
  164. afterEach(() => {
  165. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: originalWidth });
  166. vi.mocked(localStorage.getItem).mockReset();
  167. });
  168. it('moves below the header when the window narrows into the compact layout', async () => {
  169. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1440 });
  170. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  171. vi.mocked(localStorage.getItem).mockImplementation((key: string) =>
  172. key === 'embeddedCameraState_7' ? JSON.stringify({ x: 900, y: 20, width: 400, height: 300 }) : null,
  173. );
  174. const listeners: Array<(e: { matches: boolean }) => void> = [];
  175. const originalMatchMedia = window.matchMedia;
  176. window.matchMedia = ((query: string) => ({
  177. ...originalMatchMedia(query),
  178. matches: false,
  179. addEventListener: (_: string, cb: (e: { matches: boolean }) => void) => listeners.push(cb),
  180. removeEventListener: () => {},
  181. })) as typeof window.matchMedia;
  182. try {
  183. const { container } = render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />);
  184. await settle();
  185. const box = container.querySelector('.fixed') as HTMLElement;
  186. expect(box.style.top).toBe('20px');
  187. await act(async () => listeners.forEach(cb => cb({ matches: true })));
  188. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  189. } finally {
  190. window.matchMedia = originalMatchMedia;
  191. }
  192. });
  193. it('cannot be dragged over the compact header', async () => {
  194. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 390 });
  195. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  196. const originalMatchMedia = window.matchMedia;
  197. window.matchMedia = ((query: string) => ({ ...originalMatchMedia(query), matches: /max-width/.test(query) })) as typeof window.matchMedia;
  198. try {
  199. const { container } = render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />);
  200. await settle();
  201. const box = container.querySelector('.fixed') as HTMLElement;
  202. fireEvent.mouseDown(screen.getByText('P1S'), { clientX: 100, clientY: 80 });
  203. fireEvent.mouseMove(document, { clientX: 100, clientY: 0 });
  204. fireEvent.mouseUp(document);
  205. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  206. // And by touch, as on a phone.
  207. fireEvent.touchStart(screen.getByText('P1S'), { touches: [{ clientX: 100, clientY: 80 }] });
  208. fireEvent.touchMove(document, { touches: [{ clientX: 100, clientY: 0 }] });
  209. fireEvent.touchEnd(document);
  210. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  211. } finally {
  212. window.matchMedia = originalMatchMedia;
  213. }
  214. });
  215. it('keeps a position saved before the update below the compact header', async () => {
  216. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 390 });
  217. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  218. // The old default, saved by every viewer half a second after it opened.
  219. vi.mocked(localStorage.getItem).mockImplementation((key: string) =>
  220. key === 'embeddedCameraState_7' ? JSON.stringify({ x: -30, y: 20, width: 400, height: 300 }) : null,
  221. );
  222. const { container } = render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />);
  223. await settle();
  224. const box = container.querySelector('.fixed') as HTMLElement;
  225. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  226. });
  227. it('opens below the compact header and inside a phone-sized window (#2737)', async () => {
  228. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 390 });
  229. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  230. const { container } = render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />);
  231. await settle();
  232. const box = container.querySelector('.fixed') as HTMLElement;
  233. // The 56px header holds the camera launcher and the bug report.
  234. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  235. expect(parseInt(box.style.left, 10)).toBeGreaterThanOrEqual(0);
  236. expect(parseInt(box.style.left, 10) + parseInt(box.style.width, 10)).toBeLessThanOrEqual(390);
  237. });
  238. });