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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. cancel?: Function;
  124. className?: string;
  125. component: ComponentType<any>;
  126. icon: Function;
  127. labelKey: string;
  128. name: string;
  129. props?: IObject;
  130. propsUpdateFunction?: (tabState: IObject, newProps: P) => P;
  131. submit?: Function;
  132. }
  133. interface IProps extends IBaseProps {
  134. defaultTab?: string;
  135. tabs: IDialogTab<any>[];
  136. }
  137. const DialogWithTabs = ({
  138. className,
  139. defaultTab,
  140. titleKey,
  141. tabs
  142. }: IProps) => {
  143. const { classes, cx } = useStyles();
  144. const dispatch = useDispatch();
  145. const { t } = useTranslation();
  146. const [ selectedTab, setSelectedTab ] = useState<string | undefined>(defaultTab ?? tabs[0].name);
  147. const [ userSelected, setUserSelected ] = useState(false);
  148. const [ tabStates, setTabStates ] = useState(tabs.map(tab => tab.props));
  149. const clientWidth = useSelector((state: IReduxState) => state['features/base/responsive-ui'].clientWidth);
  150. const [ isMobile, setIsMobile ] = useState(false);
  151. useEffect(() => {
  152. if (clientWidth <= MOBILE_BREAKPOINT) {
  153. !isMobile && setIsMobile(true);
  154. } else {
  155. isMobile && setIsMobile(false);
  156. }
  157. }, [ clientWidth, isMobile ]);
  158. useEffect(() => {
  159. if (isMobile) {
  160. setSelectedTab(undefined);
  161. } else {
  162. setSelectedTab(defaultTab ?? tabs[0].name);
  163. }
  164. }, [ isMobile ]);
  165. const onUserSelection = useCallback((tabName?: string) => {
  166. setUserSelected(true);
  167. setSelectedTab(tabName);
  168. }, []);
  169. const back = useCallback(() => {
  170. onUserSelection(undefined);
  171. }, []);
  172. // the userSelected state is used to prevent setting focus when the user
  173. // didn't actually interact (for the first rendering for example)
  174. useEffect(() => {
  175. if (userSelected) {
  176. document.querySelector<HTMLElement>(isMobile
  177. ? `.${classes.title}`
  178. : `#${`dialogtab-button-${selectedTab}`}`
  179. )?.focus();
  180. setUserSelected(false);
  181. }
  182. }, [ isMobile, userSelected, selectedTab ]);
  183. const onClose = useCallback((isCancel = true) => {
  184. if (isCancel) {
  185. tabs.forEach(({ cancel }) => {
  186. cancel && dispatch(cancel());
  187. });
  188. }
  189. dispatch(hideDialog());
  190. }, []);
  191. const onClick = useCallback((tabName: string) => () => {
  192. onUserSelection(tabName);
  193. }, []);
  194. const onTabKeyDown = useCallback((index: number) => (event: React.KeyboardEvent<HTMLDivElement>) => {
  195. let newTab: IDialogTab<any> | null = null;
  196. if (event.key === 'ArrowUp') {
  197. newTab = index === 0 ? tabs[tabs.length - 1] : tabs[index - 1];
  198. }
  199. if (event.key === 'ArrowDown') {
  200. newTab = index === tabs.length - 1 ? tabs[0] : tabs[index + 1];
  201. }
  202. if (newTab !== null) {
  203. onUserSelection(newTab.name);
  204. }
  205. }, [ tabs.length ]);
  206. const onMobileKeyDown = useCallback((tabName: string) => (event: React.KeyboardEvent<HTMLDivElement>) => {
  207. if (event.key === ' ' || event.key === 'Enter') {
  208. onUserSelection(tabName);
  209. }
  210. }, [ classes.contentContainer ]);
  211. const getTabProps = (tabId: number) => {
  212. const tabConfiguration = tabs[tabId];
  213. const currentTabState = tabStates[tabId];
  214. if (tabConfiguration.propsUpdateFunction) {
  215. return tabConfiguration.propsUpdateFunction(
  216. currentTabState ?? {},
  217. tabConfiguration.props ?? {});
  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. {(!isMobile || !selectedTab) && (
  267. <div
  268. aria-orientation = 'vertical'
  269. className = { classes.sidebar }
  270. role = { isMobile ? undefined : 'tablist' }>
  271. <div className = { classes.titleContainer }>
  272. <MoveFocusInside>
  273. <h2
  274. className = { classes.title }
  275. tabIndex = { -1 }>
  276. {t(titleKey ?? '')}
  277. </h2>
  278. </MoveFocusInside>
  279. {isMobile && closeIcon}
  280. </div>
  281. {tabs.map((tab, index) => {
  282. const label = t(tab.labelKey);
  283. /**
  284. * When not on mobile, the items behave as tabs,
  285. * that's why we set `controls`, `role` and `selected` attributes
  286. * only when not on mobile, they are useful only for the tab behavior.
  287. */
  288. return (
  289. <ContextMenuItem
  290. accessibilityLabel = { label }
  291. className = { cx(isMobile && classes.menuItemMobile) }
  292. controls = { isMobile ? undefined : `dialogtab-content-${tab.name}` }
  293. icon = { tab.icon }
  294. id = { `dialogtab-button-${tab.name}` }
  295. key = { tab.name }
  296. onClick = { onClick(tab.name) }
  297. onKeyDown = { isMobile ? onMobileKeyDown(tab.name) : onTabKeyDown(index) }
  298. role = { isMobile ? undefined : 'tab' }
  299. selected = { tab.name === selectedTab }
  300. text = { label } />
  301. );
  302. })}
  303. </div>
  304. )}
  305. {(!isMobile || selectedTab) && (
  306. <div
  307. className = { classes.contentContainer }
  308. tabIndex = { isMobile ? -1 : undefined }>
  309. {/* DOM order is important for keyboard users: show whole heading first when on mobile… */}
  310. {isMobile && (
  311. <div className = { cx(classes.buttonContainer, classes.header) }>
  312. <span className = { classes.backContainer }>
  313. <h2
  314. className = { classes.title }
  315. tabIndex = { -1 }>
  316. {(selectedTabIndex !== null) && t(tabs[selectedTabIndex].labelKey)}
  317. </h2>
  318. <ClickableIcon
  319. accessibilityLabel = { t('dialog.Back') }
  320. icon = { IconArrowBack }
  321. id = 'modal-header-back-button'
  322. onClick = { back } />
  323. </span>
  324. {closeIcon}
  325. </div>
  326. )}
  327. {tabs.map(tab => (
  328. <div
  329. aria-labelledby = { isMobile ? undefined : `${tab.name}-button` }
  330. className = { cx(classes.content, tab.name !== selectedTab && 'hide') }
  331. id = { `dialogtab-content-${tab.name}` }
  332. key = { tab.name }
  333. role = { isMobile ? undefined : 'tabpanel' }
  334. tabIndex = { isMobile ? -1 : 0 }>
  335. { tab.name === selectedTab && selectedTabComponent }
  336. </div>
  337. ))}
  338. {/* But show the close button *after* tab panels when not on mobile (using tabs).
  339. This is so that we can tab back and forth tab buttons and tab panels easily. */}
  340. {!isMobile && (
  341. <div className = { cx(classes.buttonContainer, classes.header) }>
  342. {closeIcon}
  343. </div>
  344. )}
  345. <div
  346. className = { cx(classes.buttonContainer, classes.footer) }>
  347. <Button
  348. accessibilityLabel = { t('dialog.Cancel') }
  349. id = 'modal-dialog-cancel-button'
  350. labelKey = { 'dialog.Cancel' }
  351. onClick = { onClose }
  352. type = 'tertiary' />
  353. <Button
  354. accessibilityLabel = { t('dialog.Ok') }
  355. id = 'modal-dialog-ok-button'
  356. labelKey = { 'dialog.Ok' }
  357. onClick = { onSubmit } />
  358. </div>
  359. </div>
  360. )}
  361. </BaseDialog>
  362. );
  363. };
  364. export default DialogWithTabs;