EmbeddedCameraViewer.test.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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('offers no window to pop out to in a home-screen web app (#3419)', async () => {
  154. Object.defineProperty(navigator, 'standalone', { value: true, configurable: true });
  155. try {
  156. render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={vi.fn()} />);
  157. await settle();
  158. expect(screen.queryByRole('button', { name: 'Open in its own window' })).toBeNull();
  159. } finally {
  160. delete (navigator as Navigator & { standalone?: boolean }).standalone;
  161. }
  162. });
  163. it('keeps the overlay when a popup blocker stopped the window', async () => {
  164. vi.spyOn(window, 'open').mockReturnValue(null);
  165. const onClose = vi.fn();
  166. render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={onClose} />);
  167. await settle();
  168. fireEvent.click(screen.getByRole('button', { name: 'Open in its own window' }));
  169. expect(onClose).not.toHaveBeenCalled();
  170. });
  171. });
  172. describe('EmbeddedCameraViewer first position', () => {
  173. const originalWidth = window.innerWidth;
  174. afterEach(() => {
  175. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: originalWidth });
  176. vi.mocked(localStorage.getItem).mockReset();
  177. });
  178. it('moves below the header when the window narrows into the compact layout', async () => {
  179. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1440 });
  180. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  181. vi.mocked(localStorage.getItem).mockImplementation((key: string) =>
  182. key === 'embeddedCameraState_7' ? JSON.stringify({ x: 900, y: 20, width: 400, height: 300 }) : null,
  183. );
  184. const listeners: Array<(e: { matches: boolean }) => void> = [];
  185. const originalMatchMedia = window.matchMedia;
  186. window.matchMedia = ((query: string) => ({
  187. ...originalMatchMedia(query),
  188. matches: false,
  189. addEventListener: (_: string, cb: (e: { matches: boolean }) => void) => listeners.push(cb),
  190. removeEventListener: () => {},
  191. })) as typeof window.matchMedia;
  192. try {
  193. const { container } = render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />);
  194. await settle();
  195. const box = container.querySelector('.fixed') as HTMLElement;
  196. expect(box.style.top).toBe('20px');
  197. await act(async () => listeners.forEach(cb => cb({ matches: true })));
  198. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  199. } finally {
  200. window.matchMedia = originalMatchMedia;
  201. }
  202. });
  203. it('cannot be dragged over the compact header', async () => {
  204. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 390 });
  205. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  206. const originalMatchMedia = window.matchMedia;
  207. window.matchMedia = ((query: string) => ({ ...originalMatchMedia(query), matches: /max-width/.test(query) })) as typeof window.matchMedia;
  208. try {
  209. const { container } = render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />);
  210. await settle();
  211. const box = container.querySelector('.fixed') as HTMLElement;
  212. fireEvent.mouseDown(screen.getByText('P1S'), { clientX: 100, clientY: 80 });
  213. fireEvent.mouseMove(document, { clientX: 100, clientY: 0 });
  214. fireEvent.mouseUp(document);
  215. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  216. // And by touch, as on a phone.
  217. fireEvent.touchStart(screen.getByText('P1S'), { touches: [{ clientX: 100, clientY: 80 }] });
  218. fireEvent.touchMove(document, { touches: [{ clientX: 100, clientY: 0 }] });
  219. fireEvent.touchEnd(document);
  220. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  221. } finally {
  222. window.matchMedia = originalMatchMedia;
  223. }
  224. });
  225. it('keeps a position saved before the update below the compact header', async () => {
  226. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 390 });
  227. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  228. // The old default, saved by every viewer half a second after it opened.
  229. vi.mocked(localStorage.getItem).mockImplementation((key: string) =>
  230. key === 'embeddedCameraState_7' ? JSON.stringify({ x: -30, y: 20, width: 400, height: 300 }) : null,
  231. );
  232. const { container } = render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />);
  233. await settle();
  234. const box = container.querySelector('.fixed') as HTMLElement;
  235. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  236. });
  237. it('opens below the compact header and inside a phone-sized window (#2737)', async () => {
  238. Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 390 });
  239. server.use(http.get('/api/v1/printers/:id/camera/status', () => HttpResponse.json({ active: true, stalled: false })));
  240. const { container } = render(<EmbeddedCameraViewer printerId={7} printerName="P1S" onClose={() => {}} />);
  241. await settle();
  242. const box = container.querySelector('.fixed') as HTMLElement;
  243. // The 56px header holds the camera launcher and the bug report.
  244. expect(parseInt(box.style.top, 10)).toBeGreaterThanOrEqual(56);
  245. expect(parseInt(box.style.left, 10)).toBeGreaterThanOrEqual(0);
  246. expect(parseInt(box.style.left, 10) + parseInt(box.style.width, 10)).toBeLessThanOrEqual(390);
  247. });
  248. });