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.

DialogWithTabs.tsx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import React, { ComponentType, useCallback, useEffect, useMemo, useState } from 'react';
  2. import { MoveFocusInside } from 'react-focus-lock';
  3. import { useTranslation } from 'react-i18next';
  4. import { useDispatch, useSelector } from 'react-redux';
  5. import { makeStyles } from 'tss-react/mui';
  6. import { IReduxState } from '../../../../app/types';
  7. import { hideDialog } from '../../../dialog/actions';
  8. import { IconArrowBack, IconCloseLarge } from '../../../icons/svg';
  9. import { withPixelLineHeight } from '../../../styles/functions.web';
  10. import BaseDialog, { IProps as IBaseProps } from './BaseDialog';
  11. import Button from './Button';
  12. import ClickableIcon from './ClickableIcon';
  13. import ContextMenuItem from './ContextMenuItem';
  14. const MOBILE_BREAKPOINT = 607;
  15. const useStyles = makeStyles()(theme => {
  16. return {
  17. dialog: {
  18. flexDirection: 'row',
  19. height: '560px',
  20. '@media (min-width: 608px) and (max-width: 712px)': {
  21. width: '560px'
  22. },
  23. [`@media (max-width: ${MOBILE_BREAKPOINT}px)`]: {
  24. width: '100%',
  25. position: 'absolute',
  26. top: 0,
  27. left: 0,
  28. bottom: 0
  29. },
  30. '@media (max-width: 448px)': {
  31. height: '100%'
  32. }
  33. },
  34. sidebar: {
  35. display: 'flex',
  36. flexDirection: 'column',
  37. minWidth: '211px',
  38. maxWidth: '100%',
  39. borderRight: `1px solid ${theme.palette.ui03}`,
  40. [`@media (max-width: ${MOBILE_BREAKPOINT}px)`]: {
  41. width: '100%',
  42. borderRight: 'none'
  43. }
  44. },
  45. menuItemMobile: {
  46. paddingLeft: '24px'
  47. },
  48. titleContainer: {
  49. margin: 0,
  50. padding: '24px',
  51. paddingRight: 0,
  52. display: 'flex',
  53. flexDirection: 'row',
  54. alignItems: 'center',
  55. justifyContent: 'space-between',
  56. [`@media (max-width: ${MOBILE_BREAKPOINT}px)`]: {
  57. padding: '16px 24px'
  58. }
  59. },
  60. title: {
  61. ...withPixelLineHeight(theme.typography.heading5),
  62. color: `${theme.palette.text01} !important`,
  63. margin: 0,
  64. padding: 0
  65. },
  66. contentContainer: {
  67. position: 'relative',
  68. display: 'flex',
  69. padding: '24px',
  70. flexDirection: 'column',
  71. overflow: 'hidden',
  72. width: '100%',
  73. [`@media (max-width: ${MOBILE_BREAKPOINT}px)`]: {
  74. padding: '0'
  75. }
  76. },
  77. buttonContainer: {
  78. width: '100%',
  79. boxSizing: 'border-box',
  80. display: 'flex',
  81. alignItems: 'center',
  82. justifyContent: 'flex-end',
  83. flexGrow: 0,
  84. [`@media (max-width: ${MOBILE_BREAKPOINT}px)`]: {
  85. justifyContent: 'space-between',
  86. padding: '16px 24px'
  87. }
  88. },
  89. backContainer: {
  90. display: 'flex',
  91. flexDirection: 'row-reverse',
  92. alignItems: 'center',
  93. '& > button': {
  94. marginRight: '24px'
  95. }
  96. },
  97. content: {
  98. flexGrow: 1,
  99. overflowY: 'auto',
  100. width: '100%',
  101. boxSizing: 'border-box',
  102. [`@media (max-width: ${MOBILE_BREAKPOINT}px)`]: {
  103. padding: '0 24px'
  104. }
  105. },
  106. header: {
  107. order: -1,
  108. paddingBottom: theme.spacing(4)
  109. },
  110. footer: {
  111. justifyContent: 'flex-end',
  112. paddingTop: theme.spacing(4),
  113. '& button:last-child': {
  114. marginLeft: '16px'
  115. }
  116. }
  117. };
  118. });
  119. interface IObject {
  120. [key: string]: string | string[] | boolean | number | number[] | {} | undefined;
  121. }
  122. export interface IDialogTab<P> {
  123. className?: string;
  124. component: ComponentType<any>;
  125. icon: Function;
  126. labelKey: string;
  127. name: string;
  128. props?: IObject;
  129. propsUpdateFunction?: (tabState: IObject, newProps: P) => P;
  130. submit?: Function;
  131. }
  132. interface IProps extends IBaseProps {
  133. defaultTab?: string;
  134. tabs: IDialogTab<any>[];
  135. }
  136. const DialogWithTabs = ({
  137. className,
  138. defaultTab,
  139. titleKey,
  140. tabs
  141. }: IProps) => {
  142. const { classes, cx } = useStyles();
  143. const dispatch = useDispatch();
  144. const { t } = useTranslation();
  145. const [ selectedTab, setSelectedTab ] = useState<string | undefined>(defaultTab ?? tabs[0].name);
  146. const [ userSelected, setUserSelected ] = useState(false);
  147. const [ tabStates, setTabStates ] = useState(tabs.map(tab => tab.props));
  148. const clientWidth = useSelector((state: IReduxState) => state['features/base/responsive-ui'].clientWidth);
  149. const [ isMobile, setIsMobile ] = useState(false);
  150. useEffect(() => {
  151. if (clientWidth <= MOBILE_BREAKPOINT) {
  152. !isMobile && setIsMobile(true);
  153. } else {
  154. isMobile && setIsMobile(false);
  155. }
  156. }, [ clientWidth, isMobile ]);
  157. useEffect(() => {
  158. if (isMobile) {
  159. setSelectedTab(undefined);
  160. } else {
  161. setSelectedTab(defaultTab ?? tabs[0].name);
  162. }
  163. }, [ isMobile ]);
  164. const onUserSelection = useCallback((tabName?: string) => {
  165. setUserSelected(true);
  166. setSelectedTab(tabName);
  167. }, []);
  168. const back = useCallback(() => {
  169. onUserSelection(undefined);
  170. }, []);
  171. // the userSelected state is used to prevent setting focus when the user
  172. // didn't actually interact (for the first rendering for example)
  173. useEffect(() => {
  174. if (userSelected) {
  175. document.querySelector<HTMLElement>(isMobile
  176. ? `.${classes.title}`
  177. : `#${`dialogtab-button-${selectedTab}`}`
  178. )?.focus();
  179. setUserSelected(false);
  180. }
  181. }, [ isMobile, userSelected, selectedTab ]);
  182. const onClose = useCallback(() => {
  183. dispatch(hideDialog());
  184. }, []);
  185. const onClick = useCallback((tabName: string) => () => {
  186. onUserSelection(tabName);
  187. }, []);
  188. const onTabKeyDown = useCallback((index: number) => (event: React.KeyboardEvent<HTMLDivElement>) => {
  189. let newTab: IDialogTab<any> | null = null;
  190. if (event.key === 'ArrowUp') {
  191. newTab = index === 0 ? tabs[tabs.length - 1] : tabs[index - 1];
  192. }
  193. if (event.key === 'ArrowDown') {
  194. newTab = index === tabs.length - 1 ? tabs[0] : tabs[index + 1];
  195. }
  196. if (newTab !== null) {
  197. onUserSelection(newTab.name);
  198. }
  199. }, [ tabs.length ]);
  200. const onMobileKeyDown = useCallback((tabName: string) => (event: React.KeyboardEvent<HTMLDivElement>) => {
  201. if (event.key === ' ' || event.key === 'Enter') {
  202. onUserSelection(tabName);
  203. }
  204. }, [ classes.contentContainer ]);
  205. const getTabProps = (tabId: number) => {
  206. const tabConfiguration = tabs[tabId];
  207. const currentTabState = tabStates[tabId];
  208. if (tabConfiguration.propsUpdateFunction) {
  209. return tabConfiguration.propsUpdateFunction(
  210. currentTabState ?? {},
  211. tabConfiguration.props ?? {});
  212. }
  213. return { ...currentTabState };
  214. };
  215. const onTabStateChange = useCallback((tabId: number, state: IObject) => {
  216. const newTabStates = [ ...tabStates ];
  217. newTabStates[tabId] = state;
  218. setTabStates(newTabStates);
  219. }, [ tabStates ]);
  220. const onSubmit = useCallback(() => {
  221. tabs.forEach(({ submit }, idx) => {
  222. submit?.(tabStates[idx]);
  223. });
  224. onClose();
  225. }, [ tabs, tabStates ]);
  226. const selectedTabIndex = useMemo(() => {
  227. if (selectedTab) {
  228. return tabs.findIndex(tab => tab.name === selectedTab);
  229. }
  230. return null;
  231. }, [ selectedTab ]);
  232. const selectedTabComponent = useMemo(() => {
  233. if (selectedTabIndex !== null) {
  234. const TabComponent = tabs[selectedTabIndex].component;
  235. return (
  236. <div
  237. className = { tabs[selectedTabIndex].className }
  238. key = { tabs[selectedTabIndex].name }>
  239. <TabComponent
  240. onTabStateChange = { onTabStateChange }
  241. tabId = { selectedTabIndex }
  242. { ...getTabProps(selectedTabIndex) } />
  243. </div>
  244. );
  245. }
  246. return null;
  247. }, [ selectedTabIndex, tabStates ]);
  248. const closeIcon = useMemo(() => (
  249. <ClickableIcon
  250. accessibilityLabel = { t('dialog.accessibilityLabel.close') }
  251. icon = { IconCloseLarge }
  252. id = 'modal-header-close-button'
  253. onClick = { onClose } />
  254. ), [ onClose ]);
  255. return (
  256. <BaseDialog
  257. className = { cx(classes.dialog, className) }
  258. onClose = { onClose }
  259. size = 'large'>
  260. {(!isMobile || !selectedTab) && (
  261. <div
  262. aria-orientation = 'vertical'
  263. className = { classes.sidebar }
  264. role = { isMobile ? undefined : 'tablist' }>
  265. <div className = { classes.titleContainer }>
  266. <MoveFocusInside>
  267. <h2
  268. className = { classes.title }
  269. tabIndex = { -1 }>
  270. {t(titleKey ?? '')}
  271. </h2>
  272. </MoveFocusInside>
  273. {isMobile && closeIcon}
  274. </div>
  275. {tabs.map((tab, index) => {
  276. const label = t(tab.labelKey);
  277. /**
  278. * When not on mobile, the items behave as tabs,
  279. * that's why we set `controls`, `role` and `selected` attributes
  280. * only when not on mobile, they are useful only for the tab behavior.
  281. */
  282. return (
  283. <ContextMenuItem
  284. accessibilityLabel = { label }
  285. className = { cx(isMobile && classes.menuItemMobile) }
  286. controls = { isMobile ? undefined : `dialogtab-content-${tab.name}` }
  287. icon = { tab.icon }
  288. id = { `dialogtab-button-${tab.name}` }
  289. key = { tab.name }
  290. onClick = { onClick(tab.name) }
  291. onKeyDown = { isMobile ? onMobileKeyDown(tab.name) : onTabKeyDown(index) }
  292. role = { isMobile ? undefined : 'tab' }
  293. selected = { tab.name === selectedTab }
  294. text = { label } />
  295. );
  296. })}
  297. </div>
  298. )}
  299. {(!isMobile || selectedTab) && (
  300. <div
  301. className = { classes.contentContainer }
  302. tabIndex = { isMobile ? -1 : undefined }>
  303. {/* DOM order is important for keyboard users: show whole heading first when on mobile… */}
  304. {isMobile && (
  305. <div className = { cx(classes.buttonContainer, classes.header) }>
  306. <span className = { classes.backContainer }>
  307. <h2
  308. className = { classes.title }
  309. tabIndex = { -1 }>
  310. {(selectedTabIndex !== null) && t(tabs[selectedTabIndex].labelKey)}
  311. </h2>
  312. <ClickableIcon
  313. accessibilityLabel = { t('dialog.Back') }
  314. icon = { IconArrowBack }
  315. id = 'modal-header-back-button'
  316. onClick = { back } />
  317. </span>
  318. {closeIcon}
  319. </div>
  320. )}
  321. {tabs.map(tab => (
  322. <div
  323. aria-labelledby = { isMobile ? undefined : `${tab.name}-button` }
  324. className = { cx(classes.content, tab.name !== selectedTab && 'hide') }
  325. id = { `dialogtab-content-${tab.name}` }
  326. key = { tab.name }
  327. role = { isMobile ? undefined : 'tabpanel' }
  328. tabIndex = { isMobile ? -1 : 0 }>
  329. { tab.name === selectedTab && selectedTabComponent }
  330. </div>
  331. ))}
  332. {/* But show the close button *after* tab panels when not on mobile (using tabs).
  333. This is so that we can tab back and forth tab buttons and tab panels easily. */}
  334. {!isMobile && (
  335. <div className = { cx(classes.buttonContainer, classes.header) }>
  336. {closeIcon}
  337. </div>
  338. )}
  339. <div
  340. className = { cx(classes.buttonContainer, classes.footer) }>
  341. <Button
  342. accessibilityLabel = { t('dialog.Cancel') }
  343. id = 'modal-dialog-cancel-button'
  344. labelKey = { 'dialog.Cancel' }
  345. onClick = { onClose }
  346. type = 'tertiary' />
  347. <Button
  348. accessibilityLabel = { t('dialog.Ok') }
  349. id = 'modal-dialog-ok-button'
  350. labelKey = { 'dialog.Ok' }
  351. onClick = { onSubmit } />
  352. </div>
  353. </div>
  354. )}
  355. </BaseDialog>
  356. );
  357. };
  358. export default DialogWithTabs;