Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

VirtualBackgroundDialog.js 20KB

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