StreamOverlayBuilder.test.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /**
  2. * Tests for the streaming-overlay URL builder (#1422).
  3. *
  4. * The builder's whole output is a URL, so that is what these assert: the field
  5. * order, what is omitted at its default, and that the preview does not open a
  6. * camera stream until it is asked to.
  7. */
  8. import { describe, it, expect, beforeEach, vi } from 'vitest';
  9. import { screen, waitFor, fireEvent, act, within } from '@testing-library/react';
  10. import userEvent from '@testing-library/user-event';
  11. import { http, HttpResponse } from 'msw';
  12. import { render } from '../utils';
  13. import { server } from '../mocks/server';
  14. import { StreamOverlayBuilder } from '../../components/StreamOverlayBuilder';
  15. const printers = [
  16. { id: 1, name: 'X1 Carbon', ip_address: '192.168.1.100', serial_number: '00M09A350100001', model: 'X1C' },
  17. { id: 2, name: 'P1S', ip_address: '192.168.1.101', serial_number: '01P00A000000002', model: 'P1S' },
  18. ];
  19. // The URL is rendered inside a <code>, so read it back the way a user would.
  20. function shownUrl(): string {
  21. const code = document.querySelector('code');
  22. return code?.textContent ?? '';
  23. }
  24. describe('StreamOverlayBuilder', () => {
  25. beforeEach(() => {
  26. server.use(http.get('/api/v1/printers', () => HttpResponse.json(printers)), http.get('/api/v1/settings/overlay-logo', () => new HttpResponse(null, { status: 404 })));
  27. });
  28. it.each(['1', '2'])('provides independent orientation URLs and previews for artwork %s', async (artwork) => {
  29. const user = userEvent.setup();
  30. const copy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue();
  31. vi.stubGlobal('isSecureContext', true);
  32. const { unmount } = render(<StreamOverlayBuilder />);
  33. await screen.findByRole('option', { name: 'P1S' });
  34. await user.selectOptions(screen.getByLabelText('Artwork'), artwork);
  35. const layout = screen.getByLabelText('Layout');
  36. expect(layout).toHaveValue('landscape');
  37. await user.selectOptions(layout, 'both');
  38. fireEvent.change(screen.getByLabelText('From colour (hex)'), { target: { value: '#ff0000' } });
  39. fireEvent.change(screen.getByLabelText('To colour (hex)'), { target: { value: '#0000ff' } });
  40. if (artwork === '2') fireEvent.change(screen.getByRole('slider', { name: /Background transparency/ }), { target: { value: '65' } });
  41. expect(document.querySelectorAll('iframe')).toHaveLength(0);
  42. await user.selectOptions(screen.getByLabelText('Printer'), '2');
  43. await user.type(screen.getByLabelText(/token/i), 'bblt_example');
  44. await user.selectOptions(screen.getByLabelText('Text size'), 'large');
  45. await user.click(screen.getByLabelText('Nozzle'));
  46. await user.click(screen.getByLabelText('Camera feed'));
  47. await user.click(screen.getByRole('button', { name: 'Show preview' }));
  48. for (const orientation of ['Landscape', 'Portrait']) {
  49. const group = within(screen.getByRole('group', { name: `${orientation} URL` }));
  50. const url = new URL(group.getByRole('link', { name: 'Open' }).getAttribute('href') ?? '');
  51. expect(url.pathname).toBe('/overlay/2');
  52. expect(url.searchParams.get('progressFrom')).toBe('#ff0000');
  53. expect(url.searchParams.get('progressTo')).toBe('#0000ff');
  54. expect(url.searchParams.get('backgroundTransparency')).toBe(artwork === '2' ? '65' : null);
  55. expect(url.searchParams.get('layout')).toBe(orientation === 'Portrait' ? 'portrait' : null);
  56. expect(url.searchParams.get('token')).toBe('bblt_example');
  57. expect(url.searchParams.get('size')).toBe('large');
  58. expect(url.searchParams.get('camera')).toBe('false');
  59. expect(url.searchParams.get('show')).toContain('nozzle');
  60. expect(url.searchParams.get('artwork')).toBe(artwork === '2' ? '2' : null);
  61. await waitFor(() => expect(screen.getByTitle(`${orientation} preview`)).toHaveAttribute('src', url.href));
  62. await user.click(group.getByRole('button', { name: 'Copy' }));
  63. expect(copy).toHaveBeenLastCalledWith(url.href);
  64. }
  65. await user.click(screen.getByLabelText('Camera feed'));
  66. await user.selectOptions(screen.getByLabelText('Text size'), 'small');
  67. const fps = screen.getByLabelText('Frame rate');
  68. await user.clear(fps);
  69. await user.type(fps, '5');
  70. await waitFor(() => {
  71. for (const iframe of document.querySelectorAll('iframe')) {
  72. const params = new URL(iframe.src).searchParams;
  73. expect(params.get('camera')).toBeNull();
  74. expect(params.get('size')).toBe('small');
  75. expect(params.get('fps')).toBe('5');
  76. }
  77. });
  78. await user.selectOptions(layout, 'portrait');
  79. expect(document.querySelectorAll('iframe')).toHaveLength(1);
  80. expect(screen.queryByTitle('Landscape preview')).not.toBeInTheDocument();
  81. await user.click(screen.getByRole('button', { name: 'Hide preview' }));
  82. expect(document.querySelectorAll('iframe')).toHaveLength(0);
  83. await user.click(screen.getByRole('button', { name: 'Show preview' }));
  84. unmount();
  85. expect(document.querySelectorAll('iframe')).toHaveLength(0);
  86. copy.mockRestore();
  87. vi.unstubAllGlobals();
  88. });
  89. it('starts on the first printer with the overlay defaults', async () => {
  90. render(<StreamOverlayBuilder />);
  91. await waitFor(() => {
  92. expect(shownUrl()).toContain('/overlay/1');
  93. });
  94. // The same set parseConfig() defaults to, so the builder's starting point
  95. // and a bare /overlay/1 render the same overlay. Emitted in the overlay's
  96. // own top-to-bottom field order rather than parseConfig's listing order —
  97. // ?show= is read with includes(), so order is free to be the stable one.
  98. expect(shownUrl()).toContain('show=filename%2Cstatus%2Cprogress%2Clayers%2Ceta');
  99. // Defaults are omitted rather than spelled out — a shorter URL to paste.
  100. expect(shownUrl()).not.toContain('layout=');
  101. expect(shownUrl()).not.toContain('size=');
  102. expect(shownUrl()).not.toContain('fps=');
  103. expect(shownUrl()).not.toContain('camera=');
  104. expect(shownUrl()).not.toContain('token=');
  105. });
  106. it('keeps the model opt-in and updates the URL and preview when toggled', async () => {
  107. const user = userEvent.setup();
  108. render(<StreamOverlayBuilder />);
  109. const model = await screen.findByLabelText('Printer model');
  110. expect(model).not.toBeChecked();
  111. const originalUrl = shownUrl();
  112. await user.click(model);
  113. expect(new URL(shownUrl()).searchParams.get('show')).toBe('model,filename,status,progress,layers,eta');
  114. await user.click(screen.getByLabelText('Printer name'));
  115. expect(new URL(shownUrl()).searchParams.get('show')).toBe('printer,model,filename,status,progress,layers,eta');
  116. await user.click(screen.getByRole('button', { name: 'Show preview' }));
  117. await waitFor(() => expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', shownUrl()));
  118. await user.click(model);
  119. await user.click(screen.getByLabelText('Printer name'));
  120. expect(shownUrl()).toBe(originalUrl);
  121. await waitFor(() => expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', originalUrl));
  122. });
  123. it('opts into artwork in the URL and preview and restores the original URL', async () => {
  124. const user = userEvent.setup();
  125. render(<StreamOverlayBuilder />);
  126. const artwork = await screen.findByLabelText('Artwork');
  127. expect(artwork).toHaveValue('1');
  128. const original = shownUrl();
  129. expect(new URL(original).searchParams.has('artwork')).toBe(false);
  130. await user.selectOptions(artwork, 'Version 2');
  131. expect(new URL(shownUrl()).searchParams.get('artwork')).toBe('2');
  132. await user.click(screen.getByRole('button', { name: 'Show preview' }));
  133. await waitFor(() => expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', shownUrl()));
  134. await user.selectOptions(artwork, 'Classic');
  135. expect(shownUrl()).toBe(original);
  136. await waitFor(() => expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', original));
  137. });
  138. it('only offers background transparency for Version 2 and preserves its selection', async () => {
  139. const user = userEvent.setup();
  140. render(<StreamOverlayBuilder />);
  141. const artwork = await screen.findByLabelText('Artwork');
  142. expect(screen.queryByRole('slider', { name: /Background transparency/ })).not.toBeInTheDocument();
  143. await user.selectOptions(artwork, 'Version 2');
  144. const slider = screen.getByRole('slider', { name: /Background transparency/ });
  145. expect(slider).toHaveValue('0');
  146. expect(shownUrl()).not.toContain('backgroundTransparency');
  147. fireEvent.change(slider, { target: { value: '65' } });
  148. expect(new URL(shownUrl()).searchParams.get('backgroundTransparency')).toBe('65');
  149. await user.click(screen.getByRole('button', { name: 'Show preview' }));
  150. await waitFor(() => expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', shownUrl()));
  151. await user.selectOptions(artwork, 'Classic');
  152. expect(screen.queryByRole('slider', { name: /Background transparency/ })).not.toBeInTheDocument();
  153. expect(shownUrl()).not.toContain('backgroundTransparency');
  154. await user.selectOptions(artwork, 'Version 2');
  155. expect(screen.getByRole('slider', { name: /Background transparency/ })).toHaveValue('65');
  156. });
  157. it('switches printer', async () => {
  158. const user = userEvent.setup();
  159. render(<StreamOverlayBuilder />);
  160. await screen.findByRole('option', { name: 'P1S' });
  161. await user.selectOptions(screen.getByLabelText('Printer'), '2');
  162. await waitFor(() => expect(shownUrl()).toContain('/overlay/2'));
  163. });
  164. it('adds a temperature field the URL did not have', async () => {
  165. const user = userEvent.setup();
  166. render(<StreamOverlayBuilder />);
  167. await waitFor(() => expect(screen.getByLabelText('Nozzle')).toBeInTheDocument());
  168. await user.click(screen.getByLabelText('Nozzle'));
  169. await waitFor(() =>
  170. expect(shownUrl()).toContain('show=filename%2Cstatus%2Cprogress%2Clayers%2Ceta%2Cnozzle'),
  171. );
  172. });
  173. it('emits fields in the overlay order, not the order they were clicked', async () => {
  174. const user = userEvent.setup();
  175. render(<StreamOverlayBuilder />);
  176. // "Printer name" is first in the overlay's own top-to-bottom order, so
  177. // ticking it last must still put it at the front. Otherwise the same
  178. // selection would produce a different URL depending on click order, and a
  179. // scene file would stop being comparable to the one next to it.
  180. await waitFor(() => expect(screen.getByLabelText('Printer name')).toBeInTheDocument());
  181. await user.click(screen.getByLabelText('Printer name'));
  182. await waitFor(() => expect(shownUrl()).toContain('show=printer%2Cfilename'));
  183. });
  184. it('drops a field when its box is cleared', async () => {
  185. const user = userEvent.setup();
  186. render(<StreamOverlayBuilder />);
  187. await waitFor(() => expect(screen.getByLabelText('Layer count')).toBeInTheDocument());
  188. await user.click(screen.getByLabelText('Layer count'));
  189. await waitFor(() => expect(shownUrl()).not.toContain('layers'));
  190. expect(shownUrl()).toContain('progress');
  191. });
  192. it('emits camera=false when the camera feed is switched off', async () => {
  193. const user = userEvent.setup();
  194. render(<StreamOverlayBuilder />);
  195. await waitFor(() => expect(screen.getByLabelText('Camera feed')).toBeInTheDocument());
  196. await user.click(screen.getByLabelText('Camera feed'));
  197. await waitFor(() => expect(shownUrl()).toContain('camera=false'));
  198. });
  199. it('emits size and fps only when they differ from the defaults', async () => {
  200. const user = userEvent.setup();
  201. render(<StreamOverlayBuilder />);
  202. await waitFor(() => expect(screen.getByLabelText('Text size')).toBeInTheDocument());
  203. await user.selectOptions(screen.getByLabelText('Text size'), 'large');
  204. await waitFor(() => expect(shownUrl()).toContain('size=large'));
  205. await user.selectOptions(screen.getByLabelText('Text size'), 'medium');
  206. await waitFor(() => expect(shownUrl()).not.toContain('size='));
  207. });
  208. it('appends a token and warns that the URL is now a key', async () => {
  209. const user = userEvent.setup();
  210. render(<StreamOverlayBuilder />);
  211. await waitFor(() => expect(screen.getByLabelText(/token/i)).toBeInTheDocument());
  212. expect(screen.queryByText(/This URL contains a token/)).not.toBeInTheDocument();
  213. await user.type(screen.getByLabelText(/token/i), 'bblt_abc');
  214. await waitFor(() => expect(shownUrl()).toContain('token=bblt_abc'));
  215. expect(screen.getByText(/This URL contains a token/)).toBeInTheDocument();
  216. });
  217. it('opens no camera stream until the preview is asked for', async () => {
  218. const user = userEvent.setup();
  219. render(<StreamOverlayBuilder />);
  220. await waitFor(() => expect(screen.getByText('Show preview')).toBeInTheDocument());
  221. // An always-on preview would hold a subscriber on the printer's single
  222. // camera connection for as long as the settings tab stays open.
  223. expect(document.querySelector('iframe')).toBeNull();
  224. await user.click(screen.getByText('Show preview'));
  225. await waitFor(() => expect(document.querySelector('iframe')).not.toBeNull());
  226. expect(document.querySelector('iframe')?.getAttribute('src')).toContain('/overlay/1');
  227. });
  228. it('still builds a URL when the printer list cannot be loaded', async () => {
  229. server.use(http.get('/api/v1/printers', () => HttpResponse.json({ detail: 'nope' }, { status: 500 })));
  230. render(<StreamOverlayBuilder />);
  231. // Falls back to printer 1 rather than rendering /overlay/null — the number
  232. // is the one thing the user can fix by hand in the URL.
  233. await waitFor(() => expect(shownUrl()).toContain('/overlay/1'));
  234. });
  235. });
  236. it('adds validated gradient colours to the URL and resets to the default', async () => {
  237. render(<StreamOverlayBuilder />);
  238. const from = await screen.findByLabelText('From colour (hex)');
  239. fireEvent.change(from, { target: { value: '#ff0000' } });
  240. fireEvent.change(screen.getByLabelText('To colour (hex)'), { target: { value: '#0000ff' } });
  241. expect(new URL(shownUrl()).searchParams.get('progressFrom')).toBe('#ff0000');
  242. expect(new URL(shownUrl()).searchParams.get('progressTo')).toBe('#0000ff');
  243. fireEvent.change(from, { target: { value: 'invalid' } });
  244. expect(new URL(shownUrl()).searchParams.get('progressFrom')).toBe('#ff0000');
  245. fireEvent.click(screen.getByRole('button', { name: 'Reset colours' }));
  246. expect(shownUrl()).not.toContain('progressFrom');
  247. expect(shownUrl()).not.toContain('progressTo');
  248. });
  249. it('uploads a logo, includes it in the URL, and removes it from the preview', async () => {
  250. const user = userEvent.setup();
  251. let saved = false;
  252. const create = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:logo-preview');
  253. const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
  254. server.use(
  255. http.get('/api/v1/printers', () => HttpResponse.json(printers)),
  256. http.get('/api/v1/settings/overlay-logo', () => saved ? new HttpResponse(new Blob(['png'], { type: 'image/png' })) : new HttpResponse(null, { status: 404 })),
  257. http.post('/api/v1/settings/overlay-logo', () => { saved = true; return HttpResponse.json({ status: 'ok' }); }),
  258. http.delete('/api/v1/settings/overlay-logo', () => { saved = false; return HttpResponse.json({ status: 'ok' }); }),
  259. );
  260. try {
  261. render(<StreamOverlayBuilder />);
  262. await user.upload(await screen.findByLabelText('Upload logo'), new File(['png'], 'logo.png', { type: 'image/png' }));
  263. expect(await screen.findByRole('img', { name: 'Custom logo' })).toHaveAttribute('src', 'blob:logo-preview');
  264. expect(new URL(shownUrl()).searchParams.get('logo')).toBe('1');
  265. await user.click(screen.getByRole('button', { name: 'Show preview' }));
  266. await waitFor(() => expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', shownUrl()));
  267. const previousPreview = screen.getByTitle('Landscape preview');
  268. const previousUrl = shownUrl();
  269. await user.upload(screen.getByLabelText('Upload logo'), new File(['new png'], 'replacement.png', { type: 'image/png' }));
  270. await waitFor(() => expect(screen.getByTitle('Landscape preview')).not.toBe(previousPreview));
  271. expect(shownUrl()).toBe(previousUrl);
  272. expect(await screen.findByRole('img', { name: 'Custom logo' })).toBeInTheDocument();
  273. await user.click(screen.getByRole('button', { name: 'Remove' }));
  274. await waitFor(() => expect(screen.queryByRole('img', { name: 'Custom logo' })).not.toBeInTheDocument());
  275. expect(new URL(shownUrl()).searchParams.has('logo')).toBe(false);
  276. await waitFor(() => expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', shownUrl()));
  277. } finally {
  278. create.mockRestore();
  279. revoke.mockRestore();
  280. }
  281. });
  282. it('debounces continuous preview changes and cancels a pending reload when hidden', async () => {
  283. server.use(
  284. http.get('/api/v1/printers', () => HttpResponse.json(printers)),
  285. http.get('/api/v1/settings/overlay-logo', () => new HttpResponse(null, { status: 404 })),
  286. );
  287. render(<StreamOverlayBuilder />);
  288. await screen.findByRole('option', { name: 'X1 Carbon' });
  289. fireEvent.change(screen.getByLabelText('Artwork'), { target: { value: '2' } });
  290. fireEvent.click(screen.getByRole('button', { name: 'Show preview' }));
  291. const original = screen.getByTitle('Landscape preview');
  292. vi.useFakeTimers();
  293. try {
  294. fireEvent.change(screen.getByLabelText('From colour'), { target: { value: '#ff0000' } });
  295. act(() => vi.advanceTimersByTime(200));
  296. fireEvent.change(screen.getByRole('slider', { name: /Background transparency/ }), { target: { value: '65' } });
  297. act(() => vi.advanceTimersByTime(299));
  298. expect(screen.getByTitle('Landscape preview')).toBe(original);
  299. expect(original).not.toHaveAttribute('src', shownUrl());
  300. act(() => vi.advanceTimersByTime(1));
  301. expect(screen.getByTitle('Landscape preview')).not.toBe(original);
  302. expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', shownUrl());
  303. fireEvent.change(screen.getByLabelText('From colour'), { target: { value: '#0000ff' } });
  304. fireEvent.click(screen.getByRole('button', { name: 'Hide preview' }));
  305. act(() => vi.advanceTimersByTime(300));
  306. expect(screen.queryByTitle('Landscape preview')).not.toBeInTheDocument();
  307. fireEvent.click(screen.getByRole('button', { name: 'Show preview' }));
  308. expect(screen.getByTitle('Landscape preview')).toHaveAttribute('src', shownUrl());
  309. fireEvent.click(screen.getByRole('button', { name: 'Hide preview' }));
  310. } finally {
  311. vi.useRealTimers();
  312. }
  313. });
  314. it.each([
  315. [400, { detail: 'Logo must be a static PNG or WebP image' }, 'Logo must be a static PNG or WebP image'],
  316. [413, { detail: { message: 'Logo must be at most 2 MiB' } }, 'Logo must be at most 2 MiB'],
  317. [502, null, 'HTTP 502'],
  318. ])('shows the server upload error for status %s', async (status, body, message) => {
  319. server.use(
  320. http.get('/api/v1/printers', () => HttpResponse.json(printers)),
  321. http.get('/api/v1/settings/overlay-logo', () => new HttpResponse(null, { status: 404 })),
  322. http.post('/api/v1/settings/overlay-logo', () => body ? HttpResponse.json(body, { status }) : new HttpResponse('Bad gateway', { status })),
  323. );
  324. const user = userEvent.setup();
  325. render(<StreamOverlayBuilder />);
  326. await user.upload(screen.getByLabelText('Upload logo'), new File(['invalid'], 'logo.png', { type: 'image/png' }));
  327. expect(await screen.findByText(message)).toBeInTheDocument();
  328. expect(new URL(shownUrl()).searchParams.has('logo')).toBe(false);
  329. expect(screen.getByLabelText('Upload logo')).toBeEnabled();
  330. });