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

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