您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

VirtualBackgrounds.tsx 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /* eslint-disable lines-around-comment */
  2. // @ts-ignore
  3. import Bourne from '@hapi/bourne';
  4. // @ts-ignore
  5. import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
  6. import React, { useCallback, useEffect, useState } from 'react';
  7. import { WithTranslation } from 'react-i18next';
  8. import { connect } from 'react-redux';
  9. import { makeStyles } from 'tss-react/mui';
  10. import { IReduxState } from '../../app/types';
  11. import { getMultipleVideoSendingSupportFeatureFlag } from '../../base/config/functions.any';
  12. import { translate } from '../../base/i18n/functions';
  13. import Icon from '../../base/icons/components/Icon';
  14. import { IconCloseLarge } from '../../base/icons/svg';
  15. import { withPixelLineHeight } from '../../base/styles/functions.web';
  16. import Tooltip from '../../base/tooltip/components/Tooltip';
  17. import Spinner from '../../base/ui/components/web/Spinner';
  18. import { BACKGROUNDS_LIMIT, IMAGES, type Image, VIRTUAL_BACKGROUND_TYPE } from '../constants';
  19. import { toDataURL } from '../functions';
  20. import logger from '../logger';
  21. import UploadImageButton from './UploadImageButton';
  22. import VirtualBackgroundPreview from './VirtualBackgroundPreview';
  23. /* eslint-enable lines-around-comment */
  24. interface IProps extends WithTranslation {
  25. /**
  26. * The list of Images to choose from.
  27. */
  28. _images: Array<Image>;
  29. /**
  30. * Returns the jitsi track that will have background effect applied.
  31. */
  32. _jitsiTrack: Object;
  33. /**
  34. * The current local flip x status.
  35. */
  36. _localFlipX: boolean;
  37. /**
  38. * Whether or not multi-stream send support is enabled.
  39. */
  40. _multiStreamModeEnabled: boolean;
  41. /**
  42. * If the upload button should be displayed or not.
  43. */
  44. _showUploadButton: boolean;
  45. /**
  46. * Returns the selected virtual background object.
  47. */
  48. _virtualBackground: any;
  49. /**
  50. * The redux {@code dispatch} function.
  51. */
  52. dispatch: Function;
  53. /**
  54. * The initial options copied in the state for the {@code VirtualBackground} component.
  55. *
  56. * NOTE: currently used only for electron in order to open the dialog in the correct state after desktop sharing
  57. * selection.
  58. */
  59. initialOptions?: Object;
  60. /**
  61. * Options change handler.
  62. */
  63. onOptionsChange: Function;
  64. /**
  65. * Virtual background options.
  66. */
  67. options: any;
  68. /**
  69. * Returns the selected thumbnail identifier.
  70. */
  71. selectedThumbnail: string;
  72. }
  73. const onError = (event: any) => {
  74. event.target.style.display = 'none';
  75. };
  76. const useStyles = makeStyles()(theme => {
  77. return {
  78. virtualBackgroundLoading: {
  79. width: '100%',
  80. display: 'flex',
  81. alignItems: 'center',
  82. justifyContent: 'center',
  83. height: '50px'
  84. },
  85. container: {
  86. width: '100%',
  87. display: 'flex',
  88. flexDirection: 'column'
  89. },
  90. thumbnailContainer: {
  91. width: '100%',
  92. display: 'inline-grid',
  93. gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr',
  94. gap: theme.spacing(1),
  95. '@media (min-width: 608px) and (max-width: 712px)': {
  96. gridTemplateColumns: '1fr 1fr 1fr 1fr'
  97. },
  98. '@media (max-width: 607px)': {
  99. gridTemplateColumns: '1fr 1fr 1fr',
  100. gap: theme.spacing(2)
  101. }
  102. },
  103. thumbnail: {
  104. height: '54px',
  105. width: '100%',
  106. borderRadius: '4px',
  107. boxSizing: 'border-box',
  108. display: 'flex',
  109. alignItems: 'center',
  110. justifyContent: 'center',
  111. textAlign: 'center',
  112. ...withPixelLineHeight(theme.typography.labelBold),
  113. color: theme.palette.text01,
  114. objectFit: 'cover',
  115. [[ '&:hover', '&:focus' ] as any]: {
  116. opacity: 0.5,
  117. cursor: 'pointer',
  118. '& ~ .delete-image-icon': {
  119. display: 'block'
  120. }
  121. },
  122. '@media (max-width: 607px)': {
  123. height: '70px'
  124. }
  125. },
  126. selectedThumbnail: {
  127. border: `2px solid ${theme.palette.action01Hover}`
  128. },
  129. noneThumbnail: {
  130. backgroundColor: theme.palette.ui04
  131. },
  132. slightBlur: {
  133. boxShadow: 'inset 0 0 12px #000000',
  134. background: '#a4a4a4'
  135. },
  136. blur: {
  137. boxShadow: 'inset 0 0 12px #000000',
  138. background: '#7e8287'
  139. },
  140. storedImageContainer: {
  141. position: 'relative',
  142. display: 'flex',
  143. flexDirection: 'column',
  144. '&:focus-within .delete-image-container': {
  145. display: 'block'
  146. }
  147. },
  148. deleteImageIcon: {
  149. position: 'absolute',
  150. top: '3px',
  151. right: '3px',
  152. background: theme.palette.ui03,
  153. borderRadius: '3px',
  154. cursor: 'pointer',
  155. display: 'none',
  156. '@media (max-width: 607px)': {
  157. display: 'block',
  158. padding: '3px'
  159. },
  160. [[ '&:hover', '&:focus' ] as any]: {
  161. display: 'block'
  162. }
  163. }
  164. };
  165. });
  166. /**
  167. * Renders virtual background dialog.
  168. *
  169. * @returns {ReactElement}
  170. */
  171. function VirtualBackgrounds({
  172. _images,
  173. _jitsiTrack,
  174. _localFlipX,
  175. selectedThumbnail,
  176. _showUploadButton,
  177. _virtualBackground,
  178. onOptionsChange,
  179. options,
  180. initialOptions,
  181. t
  182. }: IProps) {
  183. const { classes, cx } = useStyles();
  184. const [ previewIsLoaded, setPreviewIsLoaded ] = useState(false);
  185. const localImages = jitsiLocalStorage.getItem('virtualBackgrounds');
  186. const [ storedImages, setStoredImages ] = useState<Array<Image>>((localImages && Bourne.parse(localImages)) || []);
  187. const [ loading, setLoading ] = useState(false);
  188. useEffect(() => {
  189. onOptionsChange({ ...initialOptions });
  190. }, []);
  191. const deleteStoredImage = useCallback(e => {
  192. const imageId = e.currentTarget.getAttribute('data-imageid');
  193. setStoredImages(storedImages.filter(item => item.id !== imageId));
  194. }, [ storedImages ]);
  195. const deleteStoredImageKeyPress = useCallback(e => {
  196. if (e.key === ' ' || e.key === 'Enter') {
  197. e.preventDefault();
  198. deleteStoredImage(e);
  199. }
  200. }, [ deleteStoredImage ]);
  201. /**
  202. * Updates stored images on local storage.
  203. */
  204. useEffect(() => {
  205. try {
  206. jitsiLocalStorage.setItem('virtualBackgrounds', JSON.stringify(storedImages));
  207. } catch (err) {
  208. // Preventing localStorage QUOTA_EXCEEDED_ERR
  209. err && setStoredImages(storedImages.slice(1));
  210. }
  211. if (storedImages.length === BACKGROUNDS_LIMIT) {
  212. setStoredImages(storedImages.slice(1));
  213. }
  214. }, [ storedImages ]);
  215. const enableBlur = useCallback(async () => {
  216. onOptionsChange({
  217. backgroundType: VIRTUAL_BACKGROUND_TYPE.BLUR,
  218. enabled: true,
  219. blurValue: 25,
  220. selectedThumbnail: 'blur'
  221. });
  222. logger.info('"Blur" option set for virtual background preview!');
  223. }, []);
  224. const enableBlurKeyPress = useCallback(e => {
  225. if (e.key === ' ' || e.key === 'Enter') {
  226. e.preventDefault();
  227. enableBlur();
  228. }
  229. }, [ enableBlur ]);
  230. const enableSlideBlur = useCallback(async () => {
  231. onOptionsChange({
  232. backgroundType: VIRTUAL_BACKGROUND_TYPE.BLUR,
  233. enabled: true,
  234. blurValue: 8,
  235. selectedThumbnail: 'slight-blur'
  236. });
  237. logger.info('"Slight-blur" option set for virtual background preview!');
  238. }, []);
  239. const enableSlideBlurKeyPress = useCallback(e => {
  240. if (e.key === ' ' || e.key === 'Enter') {
  241. e.preventDefault();
  242. enableSlideBlur();
  243. }
  244. }, [ enableSlideBlur ]);
  245. const removeBackground = useCallback(async () => {
  246. onOptionsChange({
  247. enabled: false,
  248. selectedThumbnail: 'none'
  249. });
  250. logger.info('"None" option set for virtual background preview!');
  251. }, []);
  252. const removeBackgroundKeyPress = useCallback(e => {
  253. if (e.key === ' ' || e.key === 'Enter') {
  254. e.preventDefault();
  255. removeBackground();
  256. }
  257. }, [ removeBackground ]);
  258. const setUploadedImageBackground = useCallback(async e => {
  259. const imageId = e.currentTarget.getAttribute('data-imageid');
  260. const image = storedImages.find(img => img.id === imageId);
  261. if (image) {
  262. onOptionsChange({
  263. backgroundType: 'image',
  264. enabled: true,
  265. url: image.src,
  266. selectedThumbnail: image.id
  267. });
  268. logger.info('Uploaded image set for virtual background preview!');
  269. }
  270. }, [ storedImages ]);
  271. const setImageBackground = useCallback(async e => {
  272. const imageId = e.currentTarget.getAttribute('data-imageid');
  273. const image = _images.find(img => img.id === imageId);
  274. if (image) {
  275. try {
  276. const url = await toDataURL(image.src);
  277. onOptionsChange({
  278. backgroundType: 'image',
  279. enabled: true,
  280. url,
  281. selectedThumbnail: image.id
  282. });
  283. logger.info('Image set for virtual background preview!');
  284. } catch (err) {
  285. logger.error('Could not fetch virtual background image:', err);
  286. }
  287. setLoading(false);
  288. }
  289. }, []);
  290. const setImageBackgroundKeyPress = useCallback(e => {
  291. if (e.key === ' ' || e.key === 'Enter') {
  292. e.preventDefault();
  293. setImageBackground(e);
  294. }
  295. }, [ setImageBackground ]);
  296. const setUploadedImageBackgroundKeyPress = useCallback(e => {
  297. if (e.key === ' ' || e.key === 'Enter') {
  298. e.preventDefault();
  299. setUploadedImageBackground(e);
  300. }
  301. }, [ setUploadedImageBackground ]);
  302. const loadedPreviewState = useCallback(async loaded => {
  303. await setPreviewIsLoaded(loaded);
  304. }, []);
  305. return (
  306. <>
  307. <VirtualBackgroundPreview
  308. loadedPreview = { loadedPreviewState }
  309. options = { options } />
  310. {loading ? (
  311. <div className = { classes.virtualBackgroundLoading }>
  312. <Spinner />
  313. </div>
  314. ) : (
  315. <div className = { classes.container }>
  316. {_showUploadButton
  317. && <UploadImageButton
  318. setLoading = { setLoading }
  319. setOptions = { onOptionsChange }
  320. setStoredImages = { setStoredImages }
  321. showLabel = { previewIsLoaded }
  322. storedImages = { storedImages } />}
  323. <div
  324. className = { classes.thumbnailContainer }
  325. role = 'radiogroup'
  326. tabIndex = { -1 }>
  327. <Tooltip
  328. content = { t('virtualBackground.removeBackground') }
  329. position = { 'top' }>
  330. <div
  331. aria-checked = { selectedThumbnail === 'none' }
  332. aria-label = { t('virtualBackground.removeBackground') }
  333. className = { cx(classes.thumbnail, classes.noneThumbnail,
  334. selectedThumbnail === 'none' && classes.selectedThumbnail) }
  335. onClick = { removeBackground }
  336. onKeyPress = { removeBackgroundKeyPress }
  337. role = 'radio'
  338. tabIndex = { 0 } >
  339. {t('virtualBackground.none')}
  340. </div>
  341. </Tooltip>
  342. <Tooltip
  343. content = { t('virtualBackground.slightBlur') }
  344. position = { 'top' }>
  345. <div
  346. aria-checked = { selectedThumbnail === 'slight-blur' }
  347. aria-label = { t('virtualBackground.slightBlur') }
  348. className = { cx(classes.thumbnail, classes.slightBlur,
  349. selectedThumbnail === 'slight-blur' && classes.selectedThumbnail) }
  350. onClick = { enableSlideBlur }
  351. onKeyPress = { enableSlideBlurKeyPress }
  352. role = 'radio'
  353. tabIndex = { 0 }>
  354. {t('virtualBackground.slightBlur')}
  355. </div>
  356. </Tooltip>
  357. <Tooltip
  358. content = { t('virtualBackground.blur') }
  359. position = { 'top' }>
  360. <div
  361. aria-checked = { selectedThumbnail === 'blur' }
  362. aria-label = { t('virtualBackground.blur') }
  363. className = { cx(classes.thumbnail, classes.blur,
  364. selectedThumbnail === 'blur' && classes.selectedThumbnail) }
  365. onClick = { enableBlur }
  366. onKeyPress = { enableBlurKeyPress }
  367. role = 'radio'
  368. tabIndex = { 0 }>
  369. {t('virtualBackground.blur')}
  370. </div>
  371. </Tooltip>
  372. {_images.map(image => (
  373. <Tooltip
  374. content = { (image.tooltip && t(`virtualBackground.${image.tooltip}`)) ?? '' }
  375. key = { image.id }
  376. position = { 'top' }>
  377. <img
  378. alt = { image.tooltip && t(`virtualBackground.${image.tooltip}`) }
  379. aria-checked = { options?.selectedThumbnail === image.id
  380. || selectedThumbnail === image.id }
  381. className = { cx(classes.thumbnail,
  382. (options?.selectedThumbnail === image.id
  383. || selectedThumbnail === image.id) && classes.selectedThumbnail) }
  384. data-imageid = { image.id }
  385. onClick = { setImageBackground }
  386. onError = { onError }
  387. onKeyPress = { setImageBackgroundKeyPress }
  388. role = 'radio'
  389. src = { image.src }
  390. tabIndex = { 0 } />
  391. </Tooltip>
  392. ))}
  393. {storedImages.map((image, index) => (
  394. <div
  395. className = { classes.storedImageContainer }
  396. key = { image.id }>
  397. <img
  398. alt = { t('virtualBackground.uploadedImage', { index: index + 1 }) }
  399. aria-checked = { selectedThumbnail === image.id }
  400. className = { cx(classes.thumbnail,
  401. selectedThumbnail === image.id && classes.selectedThumbnail) }
  402. data-imageid = { image.id }
  403. onClick = { setUploadedImageBackground }
  404. onError = { onError }
  405. onKeyPress = { setUploadedImageBackgroundKeyPress }
  406. role = 'radio'
  407. src = { image.src }
  408. tabIndex = { 0 } />
  409. <Icon
  410. ariaLabel = { t('virtualBackground.deleteImage') }
  411. className = { cx(classes.deleteImageIcon, 'delete-image-icon') }
  412. data-imageid = { image.id }
  413. onClick = { deleteStoredImage }
  414. onKeyPress = { deleteStoredImageKeyPress }
  415. role = 'button'
  416. size = { 16 }
  417. src = { IconCloseLarge }
  418. tabIndex = { 0 } />
  419. </div>
  420. ))}
  421. </div>
  422. </div>
  423. )}
  424. </>
  425. );
  426. }
  427. /**
  428. * Maps (parts of) the redux state to the associated props for the
  429. * {@code VirtualBackground} component.
  430. *
  431. * @param {Object} state - The Redux state.
  432. * @private
  433. * @returns {{Props}}
  434. */
  435. function _mapStateToProps(state: IReduxState) {
  436. const { localFlipX } = state['features/base/settings'];
  437. const dynamicBrandingImages = state['features/dynamic-branding'].virtualBackgrounds;
  438. const hasBrandingImages = Boolean(dynamicBrandingImages.length);
  439. return {
  440. _localFlipX: Boolean(localFlipX),
  441. _images: (hasBrandingImages && dynamicBrandingImages) || IMAGES,
  442. _virtualBackground: state['features/virtual-background'],
  443. _showUploadButton: !state['features/base/config'].disableAddingBackgroundImages,
  444. _multiStreamModeEnabled: getMultipleVideoSendingSupportFeatureFlag(state)
  445. };
  446. }
  447. export default connect(_mapStateToProps)(translate(VirtualBackgrounds));