You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VirtualBackgroundDialog.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. // @flow
  2. import Spinner from '@atlaskit/spinner';
  3. import Bourne from '@hapi/bourne';
  4. import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
  5. import React, { useState, useEffect, useCallback, useRef } from 'react';
  6. import uuid from 'uuid';
  7. import { Dialog, hideDialog, openDialog } from '../../base/dialog';
  8. import { translate } from '../../base/i18n';
  9. import { Icon, IconCloseSmall, IconPlusCircle, IconShareDesktop } from '../../base/icons';
  10. import { browser, JitsiTrackErrors } from '../../base/lib-jitsi-meet';
  11. import { createLocalTrack } from '../../base/lib-jitsi-meet/functions';
  12. import { VIDEO_TYPE } from '../../base/media';
  13. import { connect } from '../../base/redux';
  14. import { updateSettings } from '../../base/settings';
  15. import { Tooltip } from '../../base/tooltip';
  16. import { getLocalVideoTrack } from '../../base/tracks';
  17. import { showErrorNotification } from '../../notifications';
  18. import { toggleBackgroundEffect } from '../actions';
  19. import { VIRTUAL_BACKGROUND_TYPE } from '../constants';
  20. import { resizeImage, toDataURL } from '../functions';
  21. import logger from '../logger';
  22. import VirtualBackgroundPreview from './VirtualBackgroundPreview';
  23. type Image = {
  24. tooltip?: string,
  25. id: string,
  26. src: string
  27. }
  28. // The limit of virtual background uploads is 24. When the number
  29. // of uploads is 25 we trigger the deleteStoredImage function to delete
  30. // the first/oldest uploaded background.
  31. const backgroundsLimit = 25;
  32. const images: Array<Image> = [
  33. {
  34. tooltip: 'image1',
  35. id: '1',
  36. src: 'images/virtual-background/background-1.jpg'
  37. },
  38. {
  39. tooltip: 'image2',
  40. id: '2',
  41. src: 'images/virtual-background/background-2.jpg'
  42. },
  43. {
  44. tooltip: 'image3',
  45. id: '3',
  46. src: 'images/virtual-background/background-3.jpg'
  47. },
  48. {
  49. tooltip: 'image4',
  50. id: '4',
  51. src: 'images/virtual-background/background-4.jpg'
  52. },
  53. {
  54. tooltip: 'image5',
  55. id: '5',
  56. src: 'images/virtual-background/background-5.jpg'
  57. },
  58. {
  59. tooltip: 'image6',
  60. id: '6',
  61. src: 'images/virtual-background/background-6.jpg'
  62. },
  63. {
  64. tooltip: 'image7',
  65. id: '7',
  66. src: 'images/virtual-background/background-7.jpg'
  67. }
  68. ];
  69. type Props = {
  70. /**
  71. * The current local flip x status.
  72. */
  73. _localFlipX: boolean,
  74. /**
  75. * Returns the jitsi track that will have backgraund effect applied.
  76. */
  77. _jitsiTrack: Object,
  78. /**
  79. * Returns the selected thumbnail identifier.
  80. */
  81. _selectedThumbnail: string,
  82. /**
  83. * Returns the selected virtual background object.
  84. */
  85. _virtualBackground: Object,
  86. /**
  87. * The redux {@code dispatch} function.
  88. */
  89. dispatch: Function,
  90. /**
  91. * The initial options copied in the state for the {@code VirtualBackground} component.
  92. *
  93. * NOTE: currently used only for electron in order to open the dialog in the correct state after desktop sharing
  94. * selection.
  95. */
  96. initialOptions: Object,
  97. /**
  98. * Invoked to obtain translated strings.
  99. */
  100. t: Function
  101. };
  102. const onError = event => {
  103. event.target.style.display = 'none';
  104. };
  105. /**
  106. * Maps (parts of) the redux state to the associated props for the
  107. * {@code VirtualBackground} component.
  108. *
  109. * @param {Object} state - The Redux state.
  110. * @private
  111. * @returns {{Props}}
  112. */
  113. function _mapStateToProps(state): Object {
  114. const { localFlipX } = state['features/base/settings'];
  115. return {
  116. _localFlipX: Boolean(localFlipX),
  117. _virtualBackground: state['features/virtual-background'],
  118. _selectedThumbnail: state['features/virtual-background'].selectedThumbnail,
  119. _jitsiTrack: getLocalVideoTrack(state['features/base/tracks'])?.jitsiTrack
  120. };
  121. }
  122. const VirtualBackgroundDialog = translate(connect(_mapStateToProps)(VirtualBackground));
  123. /**
  124. * Renders virtual background dialog.
  125. *
  126. * @returns {ReactElement}
  127. */
  128. function VirtualBackground({
  129. _localFlipX,
  130. _jitsiTrack,
  131. _selectedThumbnail,
  132. _virtualBackground,
  133. dispatch,
  134. initialOptions,
  135. t
  136. }: Props) {
  137. const [ options, setOptions ] = useState({ ...initialOptions });
  138. const localImages = jitsiLocalStorage.getItem('virtualBackgrounds');
  139. const [ storedImages, setStoredImages ] = useState<Array<Image>>((localImages && Bourne.parse(localImages)) || []);
  140. const [ loading, setLoading ] = useState(false);
  141. const uploadImageButton: Object = useRef(null);
  142. const [ activeDesktopVideo ] = useState(_virtualBackground?.virtualSource?.videoType === VIDEO_TYPE.DESKTOP
  143. ? _virtualBackground.virtualSource
  144. : null);
  145. const [ initialVirtualBackground ] = useState(_virtualBackground);
  146. const deleteStoredImage = useCallback(e => {
  147. const imageId = e.currentTarget.getAttribute('data-imageid');
  148. setStoredImages(storedImages.filter(item => item.id !== imageId));
  149. }, [ storedImages ]);
  150. const deleteStoredImageKeyPress = useCallback(e => {
  151. if (e.key === ' ' || e.key === 'Enter') {
  152. e.preventDefault();
  153. deleteStoredImage(e);
  154. }
  155. }, [ deleteStoredImage ]);
  156. /**
  157. * Updates stored images on local storage.
  158. */
  159. useEffect(() => {
  160. try {
  161. jitsiLocalStorage.setItem('virtualBackgrounds', JSON.stringify(storedImages));
  162. } catch (err) {
  163. // Preventing localStorage QUOTA_EXCEEDED_ERR
  164. err && setStoredImages(storedImages.slice(1));
  165. }
  166. if (storedImages.length === backgroundsLimit) {
  167. setStoredImages(storedImages.slice(1));
  168. }
  169. }, [ storedImages ]);
  170. const enableBlur = useCallback(async () => {
  171. setOptions({
  172. backgroundType: VIRTUAL_BACKGROUND_TYPE.BLUR,
  173. enabled: true,
  174. blurValue: 25,
  175. selectedThumbnail: 'blur'
  176. });
  177. }, []);
  178. const enableBlurKeyPress = useCallback(e => {
  179. if (e.key === ' ' || e.key === 'Enter') {
  180. e.preventDefault();
  181. enableBlur();
  182. }
  183. }, [ enableBlur ]);
  184. const enableSlideBlur = useCallback(async () => {
  185. setOptions({
  186. backgroundType: VIRTUAL_BACKGROUND_TYPE.BLUR,
  187. enabled: true,
  188. blurValue: 8,
  189. selectedThumbnail: 'slight-blur'
  190. });
  191. }, []);
  192. const enableSlideBlurKeyPress = useCallback(e => {
  193. if (e.key === ' ' || e.key === 'Enter') {
  194. e.preventDefault();
  195. enableSlideBlur();
  196. }
  197. }, [ enableSlideBlur ]);
  198. const shareDesktop = useCallback(async () => {
  199. let isCancelled = false, url;
  200. try {
  201. url = await createLocalTrack('desktop', '');
  202. } catch (e) {
  203. if (e.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  204. isCancelled = true;
  205. } else {
  206. logger.error(e);
  207. }
  208. }
  209. if (!url) {
  210. if (!isCancelled) {
  211. dispatch(showErrorNotification({
  212. titleKey: 'virtualBackground.desktopShareError'
  213. }));
  214. logger.error('Could not create desktop share as a virtual background!');
  215. }
  216. /**
  217. * For electron createLocalTrack will open the {@code DesktopPicker} dialog and hide the
  218. * {@code VirtualBackgroundDialog}. That's why we need to reopen the {@code VirtualBackgroundDialog}
  219. * and restore the current state through {@code initialOptions} prop.
  220. */
  221. if (browser.isElectron()) {
  222. dispatch(openDialog(VirtualBackgroundDialog, { initialOptions: options }));
  223. }
  224. return;
  225. }
  226. const newOptions = {
  227. backgroundType: VIRTUAL_BACKGROUND_TYPE.DESKTOP_SHARE,
  228. enabled: true,
  229. selectedThumbnail: 'desktop-share',
  230. url
  231. };
  232. /**
  233. * For electron createLocalTrack will open the {@code DesktopPicker} dialog and hide the
  234. * {@code VirtualBackgroundDialog}. That's why we need to reopen the {@code VirtualBackgroundDialog}
  235. * and force it to show desktop share virtual background through {@code initialOptions} prop.
  236. */
  237. if (browser.isElectron()) {
  238. dispatch(openDialog(VirtualBackgroundDialog, { initialOptions: newOptions }));
  239. } else {
  240. setOptions(newOptions);
  241. }
  242. }, [ dispatch, options ]);
  243. const shareDesktopKeyPress = useCallback(e => {
  244. if (e.key === ' ' || e.key === 'Enter') {
  245. e.preventDefault();
  246. shareDesktop();
  247. }
  248. }, [ shareDesktop ]);
  249. const removeBackground = useCallback(async () => {
  250. setOptions({
  251. enabled: false,
  252. selectedThumbnail: 'none'
  253. });
  254. }, []);
  255. const removeBackgroundKeyPress = useCallback(e => {
  256. if (e.key === ' ' || e.key === 'Enter') {
  257. e.preventDefault();
  258. removeBackground();
  259. }
  260. }, [ removeBackground ]);
  261. const setUploadedImageBackground = useCallback(async e => {
  262. const imageId = e.currentTarget.getAttribute('data-imageid');
  263. const image = storedImages.find(img => img.id === imageId);
  264. if (image) {
  265. setOptions({
  266. backgroundType: 'image',
  267. enabled: true,
  268. url: image.src,
  269. selectedThumbnail: image.id
  270. });
  271. }
  272. }, [ storedImages ]);
  273. const setImageBackground = useCallback(async e => {
  274. const imageId = e.currentTarget.getAttribute('data-imageid');
  275. const image = images.find(img => img.id === imageId);
  276. if (image) {
  277. const url = await toDataURL(image.src);
  278. setOptions({
  279. backgroundType: 'image',
  280. enabled: true,
  281. url,
  282. selectedThumbnail: image.id
  283. });
  284. setLoading(false);
  285. }
  286. }, []);
  287. const uploadImage = useCallback(async e => {
  288. const reader = new FileReader();
  289. const imageFile = e.target.files;
  290. reader.readAsDataURL(imageFile[0]);
  291. reader.onload = async () => {
  292. const url = await resizeImage(reader.result);
  293. const uuId = uuid.v4();
  294. setStoredImages([
  295. ...storedImages,
  296. {
  297. id: uuId,
  298. src: url
  299. }
  300. ]);
  301. setOptions({
  302. backgroundType: VIRTUAL_BACKGROUND_TYPE.IMAGE,
  303. enabled: true,
  304. url,
  305. selectedThumbnail: uuId
  306. });
  307. };
  308. reader.onerror = () => {
  309. setLoading(false);
  310. logger.error('Failed to upload virtual image!');
  311. };
  312. }, [ dispatch, storedImages ]);
  313. const uploadImageKeyPress = useCallback(e => {
  314. if (uploadImageButton.current && (e.key === ' ' || e.key === 'Enter')) {
  315. e.preventDefault();
  316. uploadImageButton.current.click();
  317. }
  318. }, [ uploadImageButton.current ]);
  319. const setImageBackgroundKeyPress = useCallback(e => {
  320. if (e.key === ' ' || e.key === 'Enter') {
  321. e.preventDefault();
  322. setImageBackground(e);
  323. }
  324. }, [ setImageBackground ]);
  325. const setUploadedImageBackgroundKeyPress = useCallback(e => {
  326. if (e.key === ' ' || e.key === 'Enter') {
  327. e.preventDefault();
  328. setUploadedImageBackground(e);
  329. }
  330. }, [ setUploadedImageBackground ]);
  331. const applyVirtualBackground = useCallback(async () => {
  332. if (activeDesktopVideo) {
  333. await activeDesktopVideo.dispose();
  334. }
  335. setLoading(true);
  336. await dispatch(toggleBackgroundEffect(options, _jitsiTrack));
  337. await setLoading(false);
  338. if (_localFlipX && options.backgroundType === VIRTUAL_BACKGROUND_TYPE.DESKTOP_SHARE) {
  339. dispatch(updateSettings({
  340. localFlipX: !_localFlipX
  341. }));
  342. }
  343. dispatch(hideDialog());
  344. }, [ dispatch, options, _localFlipX ]);
  345. // Prevent the selection of a new virtual background if it has not been applied by default
  346. const cancelVirtualBackground = useCallback(async () => {
  347. await setOptions({
  348. backgroundType: initialVirtualBackground.backgroundType,
  349. enabled: initialVirtualBackground.backgroundEffectEnabled,
  350. url: initialVirtualBackground.virtualSource,
  351. selectedThumbnail: initialVirtualBackground.selectedThumbnail,
  352. blurValue: initialVirtualBackground.blurValue
  353. });
  354. dispatch(hideDialog());
  355. });
  356. return (
  357. <Dialog
  358. hideCancelButton = { false }
  359. okKey = { 'virtualBackground.apply' }
  360. onCancel = { cancelVirtualBackground }
  361. onSubmit = { applyVirtualBackground }
  362. submitDisabled = { !options || loading }
  363. titleKey = { 'virtualBackground.title' } >
  364. <VirtualBackgroundPreview options = { options } />
  365. {loading ? (
  366. <div className = 'virtual-background-loading'>
  367. <Spinner
  368. isCompleting = { false }
  369. size = 'medium' />
  370. </div>
  371. ) : (
  372. <div>
  373. <label
  374. aria-label = { t('virtualBackground.uploadImage') }
  375. className = 'file-upload-label'
  376. htmlFor = 'file-upload'
  377. onKeyPress = { uploadImageKeyPress }
  378. tabIndex = { 0 } >
  379. <Icon
  380. className = { 'add-background' }
  381. size = { 20 }
  382. src = { IconPlusCircle } />
  383. {t('virtualBackground.addBackground')}
  384. </label>
  385. <input
  386. accept = 'image/*'
  387. className = 'file-upload-btn'
  388. id = 'file-upload'
  389. onChange = { uploadImage }
  390. ref = { uploadImageButton }
  391. type = 'file' />
  392. <div
  393. className = 'virtual-background-dialog'
  394. role = 'radiogroup'
  395. tabIndex = '-1'>
  396. <Tooltip
  397. content = { t('virtualBackground.removeBackground') }
  398. position = { 'top' }>
  399. <div
  400. aria-checked = { _selectedThumbnail === 'none' }
  401. aria-label = { t('virtualBackground.removeBackground') }
  402. className = { _selectedThumbnail === 'none' ? 'background-option none-selected'
  403. : 'background-option virtual-background-none' }
  404. onClick = { removeBackground }
  405. onKeyPress = { removeBackgroundKeyPress }
  406. role = 'radio'
  407. tabIndex = { 0 } >
  408. {t('virtualBackground.none')}
  409. </div>
  410. </Tooltip>
  411. <Tooltip
  412. content = { t('virtualBackground.slightBlur') }
  413. position = { 'top' }>
  414. <div
  415. aria-checked = { _selectedThumbnail === 'slight-blur' }
  416. aria-label = { t('virtualBackground.slightBlur') }
  417. className = { _selectedThumbnail === 'slight-blur'
  418. ? 'background-option slight-blur-selected' : 'background-option slight-blur' }
  419. onClick = { enableSlideBlur }
  420. onKeyPress = { enableSlideBlurKeyPress }
  421. role = 'radio'
  422. tabIndex = { 0 }>
  423. {t('virtualBackground.slightBlur')}
  424. </div>
  425. </Tooltip>
  426. <Tooltip
  427. content = { t('virtualBackground.blur') }
  428. position = { 'top' }>
  429. <div
  430. aria-checked = { _selectedThumbnail === 'blur' }
  431. aria-label = { t('virtualBackground.blur') }
  432. className = { _selectedThumbnail === 'blur' ? 'background-option blur-selected'
  433. : 'background-option blur' }
  434. onClick = { enableBlur }
  435. onKeyPress = { enableBlurKeyPress }
  436. role = 'radio'
  437. tabIndex = { 0 }>
  438. {t('virtualBackground.blur')}
  439. </div>
  440. </Tooltip>
  441. <Tooltip
  442. content = { t('virtualBackground.desktopShare') }
  443. position = { 'top' }>
  444. <div
  445. aria-checked = { _selectedThumbnail === 'desktop-share' }
  446. aria-label = { t('virtualBackground.desktopShare') }
  447. className = { _selectedThumbnail === 'desktop-share'
  448. ? 'background-option desktop-share-selected'
  449. : 'background-option desktop-share' }
  450. onClick = { shareDesktop }
  451. onKeyPress = { shareDesktopKeyPress }
  452. role = 'radio'
  453. tabIndex = { 0 }>
  454. <Icon
  455. className = 'share-desktop-icon'
  456. size = { 30 }
  457. src = { IconShareDesktop } />
  458. </div>
  459. </Tooltip>
  460. {images.map(image => (
  461. <Tooltip
  462. content = { image.tooltip && t(`virtualBackground.${image.tooltip}`) }
  463. key = { image.id }
  464. position = { 'top' }>
  465. <img
  466. alt = { image.tooltip && t(`virtualBackground.${image.tooltip}`) }
  467. aria-checked = { options.selectedThumbnail === image.id
  468. || _selectedThumbnail === image.id }
  469. className = {
  470. options.selectedThumbnail === image.id || _selectedThumbnail === image.id
  471. ? 'background-option thumbnail-selected' : 'background-option thumbnail' }
  472. data-imageid = { image.id }
  473. onClick = { setImageBackground }
  474. onError = { onError }
  475. onKeyPress = { setImageBackgroundKeyPress }
  476. role = 'radio'
  477. src = { image.src }
  478. tabIndex = { 0 } />
  479. </Tooltip>
  480. ))}
  481. {storedImages.map((image, index) => (
  482. <div
  483. className = { 'thumbnail-container' }
  484. key = { image.id }>
  485. <img
  486. alt = { t('virtualBackground.uploadedImage', { index: index + 1 }) }
  487. aria-checked = { _selectedThumbnail === image.id }
  488. className = { _selectedThumbnail === image.id
  489. ? 'background-option thumbnail-selected' : 'background-option thumbnail' }
  490. data-imageid = { image.id }
  491. onClick = { setUploadedImageBackground }
  492. onError = { onError }
  493. onKeyPress = { setUploadedImageBackgroundKeyPress }
  494. role = 'radio'
  495. src = { image.src }
  496. tabIndex = { 0 } />
  497. <Icon
  498. ariaLabel = { t('virtualBackground.deleteImage') }
  499. className = { 'delete-image-icon' }
  500. data-imageid = { image.id }
  501. onClick = { deleteStoredImage }
  502. onKeyPress = { deleteStoredImageKeyPress }
  503. role = 'button'
  504. size = { 15 }
  505. src = { IconCloseSmall }
  506. tabIndex = { 0 } />
  507. </div>
  508. ))}
  509. </div>
  510. </div>
  511. )}
  512. </Dialog>
  513. );
  514. }
  515. export default VirtualBackgroundDialog;