GrantSelector.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import React, { useCallback, useEffect, useState } from 'react';
  2. import {
  3. PageGrant, GroupType, getIdForRef,
  4. } from '@growi/core';
  5. import { LoadingSpinner } from '@growi/ui/dist/components';
  6. import { useTranslation } from 'next-i18next';
  7. import {
  8. UncontrolledDropdown,
  9. DropdownToggle, DropdownMenu, DropdownItem,
  10. Modal, ModalHeader, ModalBody,
  11. } from 'reactstrap';
  12. import type { UserRelatedGroupsData } from '~/interfaces/page';
  13. import { UserGroupPageGrantStatus } from '~/interfaces/page';
  14. import { useCurrentUser } from '~/stores/context';
  15. import { useCurrentPageId, useSWRxCurrentGrantData } from '~/stores/page';
  16. import { useSelectedGrant } from '~/stores/ui';
  17. const AVAILABLE_GRANTS = [
  18. {
  19. grant: PageGrant.GRANT_PUBLIC, iconName: 'group', btnStyleClass: 'outline-info', label: 'Public',
  20. },
  21. {
  22. grant: PageGrant.GRANT_RESTRICTED, iconName: 'link', btnStyleClass: 'outline-success', label: 'Anyone with the link',
  23. },
  24. // { grant: 3, iconClass: '', label: 'Specified users only' },
  25. {
  26. grant: PageGrant.GRANT_OWNER, iconName: 'lock', btnStyleClass: 'outline-danger', label: 'Only me',
  27. },
  28. {
  29. grant: PageGrant.GRANT_USER_GROUP,
  30. iconName: 'more_horiz',
  31. btnStyleClass: 'outline-warning',
  32. label: 'Only inside the group',
  33. reselectLabel: 'Reselect the group',
  34. },
  35. ];
  36. type Props = {
  37. disabled?: boolean,
  38. openInModal?: boolean,
  39. }
  40. /**
  41. * Page grant select component
  42. */
  43. export const GrantSelector = (props: Props): JSX.Element => {
  44. const { t } = useTranslation();
  45. const {
  46. disabled,
  47. openInModal,
  48. } = props;
  49. const [isSelectGroupModalShown, setIsSelectGroupModalShown] = useState(false);
  50. const { data: currentUser } = useCurrentUser();
  51. const shouldFetch = isSelectGroupModalShown;
  52. const { data: selectedGrant, mutate: mutateSelectedGrant } = useSelectedGrant();
  53. const { data: currentPageId } = useCurrentPageId();
  54. const { data: grantData } = useSWRxCurrentGrantData(currentPageId);
  55. const currentPageGrantData = grantData?.grantData.currentPageGrant;
  56. const groupGrantData = currentPageGrantData?.groupGrantData;
  57. const applyCurrentPageGrantToSelectedGrant = useCallback(() => {
  58. const currentPageGrant = grantData?.grantData.currentPageGrant;
  59. if (currentPageGrant == null) return;
  60. const userRelatedGrantedGroups = currentPageGrant.groupGrantData
  61. ?.userRelatedGroups.filter(group => group.status === UserGroupPageGrantStatus.isGranted)?.map((group) => {
  62. return { item: group.id, type: group.type };
  63. }) ?? [];
  64. mutateSelectedGrant({
  65. grant: currentPageGrant.grant,
  66. userRelatedGrantedGroups,
  67. });
  68. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  69. // sync grant data
  70. useEffect(() => {
  71. applyCurrentPageGrantToSelectedGrant();
  72. }, [applyCurrentPageGrantToSelectedGrant]);
  73. const showSelectGroupModal = useCallback(() => {
  74. setIsSelectGroupModalShown(true);
  75. }, []);
  76. /**
  77. * change event handler for grant selector
  78. */
  79. const changeGrantHandler = useCallback((grant: PageGrant) => {
  80. // select group
  81. if (grant === 5) {
  82. if (selectedGrant?.grant !== 5) applyCurrentPageGrantToSelectedGrant();
  83. showSelectGroupModal();
  84. return;
  85. }
  86. mutateSelectedGrant({ grant, userRelatedGrantedGroups: undefined });
  87. }, [mutateSelectedGrant, showSelectGroupModal, applyCurrentPageGrantToSelectedGrant, selectedGrant?.grant]);
  88. const groupListItemClickHandler = useCallback((clickedGroup: UserRelatedGroupsData) => {
  89. const userRelatedGrantedGroups = selectedGrant?.userRelatedGrantedGroups ?? [];
  90. let userRelatedGrantedGroupsCopy = [...userRelatedGrantedGroups];
  91. if (userRelatedGrantedGroupsCopy.find(group => getIdForRef(group.item) === clickedGroup.id) == null) {
  92. const grantGroupInfo = { item: clickedGroup.id, type: clickedGroup.type };
  93. userRelatedGrantedGroupsCopy.push(grantGroupInfo);
  94. }
  95. else {
  96. userRelatedGrantedGroupsCopy = userRelatedGrantedGroupsCopy.filter(group => getIdForRef(group.item) !== clickedGroup.id);
  97. }
  98. mutateSelectedGrant({ grant: 5, userRelatedGrantedGroups: userRelatedGrantedGroupsCopy });
  99. }, [mutateSelectedGrant, selectedGrant?.userRelatedGrantedGroups]);
  100. /**
  101. * Render grant selector DOM.
  102. */
  103. const renderGrantSelector = useCallback(() => {
  104. let dropdownToggleBtnColor;
  105. let dropdownToggleLabelElm;
  106. const userRelatedGrantedGroups = groupGrantData?.userRelatedGroups.filter((group) => {
  107. return selectedGrant?.userRelatedGrantedGroups?.some(grantedGroup => getIdForRef(grantedGroup.item) === group.id);
  108. }) ?? [];
  109. const nonUserRelatedGrantedGroups = groupGrantData?.nonUserRelatedGrantedGroups ?? [];
  110. const dropdownMenuElems = AVAILABLE_GRANTS.map((opt) => {
  111. const label = ((opt.grant === 5 && opt.reselectLabel != null) && userRelatedGrantedGroups.length > 0)
  112. ? opt.reselectLabel // when grantGroup is selected
  113. : opt.label;
  114. const labelElm = (
  115. <span className={openInModal ? 'py-2' : ''}>
  116. <span className="material-symbols-outlined me-2">{opt.iconName}</span>
  117. <span className="label">{t(label)}</span>
  118. </span>
  119. );
  120. // set dropdownToggleBtnColor, dropdownToggleLabelElm
  121. if (opt.grant === 1 || opt.grant === selectedGrant?.grant) {
  122. dropdownToggleBtnColor = opt.btnStyleClass;
  123. dropdownToggleLabelElm = labelElm;
  124. }
  125. return <DropdownItem key={opt.grant} onClick={() => changeGrantHandler(opt.grant)}>{labelElm}</DropdownItem>;
  126. });
  127. // add specified group option
  128. if (selectedGrant?.grant === PageGrant.GRANT_USER_GROUP && (userRelatedGrantedGroups.length > 0 || nonUserRelatedGrantedGroups.length > 0)) {
  129. const grantedGroupNames = [...userRelatedGrantedGroups.map(group => group.name), ...nonUserRelatedGrantedGroups.map(group => group.name)];
  130. const labelElm = (
  131. <span>
  132. <span className="material-symbols-outlined me-1">account_tree</span>
  133. <span className="label">
  134. {grantedGroupNames.length > 1
  135. ? (
  136. // substring for group name truncate
  137. <span>
  138. {`${grantedGroupNames[0].substring(0, 30)}, ... `}
  139. <span className="badge bg-primary">+{grantedGroupNames.length - 1}</span>
  140. </span>
  141. ) : grantedGroupNames[0].substring(0, 30)}
  142. </span>
  143. </span>
  144. );
  145. // set dropdownToggleLabelElm
  146. dropdownToggleLabelElm = labelElm;
  147. dropdownMenuElems.push(<DropdownItem key="groupSelected">{labelElm}</DropdownItem>);
  148. }
  149. return (
  150. <div className="grw-grant-selector mb-0" data-testid="grw-grant-selector">
  151. <UncontrolledDropdown direction={openInModal ? 'down' : 'up'} size="sm">
  152. <DropdownToggle
  153. color={dropdownToggleBtnColor}
  154. caret
  155. className="w-100 text-truncate d-flex justify-content-between align-items-center"
  156. disabled={disabled}
  157. >
  158. {dropdownToggleLabelElm}
  159. </DropdownToggle>
  160. <DropdownMenu data-testid="grw-grant-selector-dropdown-menu" container={openInModal ? '' : 'body'}>
  161. {dropdownMenuElems}
  162. </DropdownMenu>
  163. </UncontrolledDropdown>
  164. </div>
  165. );
  166. }, [changeGrantHandler, disabled, groupGrantData, selectedGrant, t, openInModal]);
  167. /**
  168. * Render select grantgroup modal.
  169. */
  170. const renderSelectGroupModalContent = useCallback(() => {
  171. if (!shouldFetch) {
  172. return <></>;
  173. }
  174. // show spinner
  175. if (groupGrantData == null) {
  176. return (
  177. <div className="my-3 text-center">
  178. <LoadingSpinner className="mx-auto text-muted fs-4" />
  179. </div>
  180. );
  181. }
  182. const { userRelatedGroups, nonUserRelatedGrantedGroups } = groupGrantData;
  183. if (userRelatedGroups.length === 0) {
  184. return (
  185. <div>
  186. <h4>{t('user_group.belonging_to_no_group')}</h4>
  187. { currentUser?.admin && (
  188. <p><a href="/admin/user-groups"><span className="material-symbols-outlined me-1">login</span>{t('user_group.manage_user_groups')}</a></p>
  189. ) }
  190. </div>
  191. );
  192. }
  193. return (
  194. <div className="d-flex flex-column">
  195. { userRelatedGroups.map((group) => {
  196. const isGroupGranted = selectedGrant?.userRelatedGrantedGroups?.some(grantedGroup => getIdForRef(grantedGroup.item) === group.id);
  197. const cannotGrantGroup = group.status === UserGroupPageGrantStatus.cannotGrant;
  198. const activeClass = isGroupGranted ? 'active' : '';
  199. return (
  200. <button
  201. className={`btn btn-outline-primary d-flex justify-content-start mb-3 mx-4 align-items-center p-3 ${activeClass}`}
  202. type="button"
  203. key={group.id}
  204. onClick={() => groupListItemClickHandler(group)}
  205. disabled={cannotGrantGroup}
  206. >
  207. <input type="checkbox" checked={isGroupGranted} disabled={cannotGrantGroup} />
  208. <p className="ms-3 mb-0">{group.name}</p>
  209. {group.type === GroupType.externalUserGroup && <span className="ms-2 badge badge-pill badge-info">{group.provider}</span>}
  210. {/* TODO: Replace <div className="small">(TBD) List group members</div> */}
  211. </button>
  212. );
  213. }) }
  214. { nonUserRelatedGrantedGroups.map((group) => {
  215. return (
  216. <button
  217. className="btn btn-outline-primary d-flex justify-content-start mb-3 mx-4 align-items-center p-3 active"
  218. type="button"
  219. key={group.id}
  220. disabled
  221. >
  222. <input type="checkbox" checked disabled />
  223. <p className="ms-3 mb-0">{group.name}</p>
  224. {group.type === GroupType.externalUserGroup && <span className="ms-2 badge badge-pill badge-info">{group.provider}</span>}
  225. {/* TODO: Replace <div className="small">(TBD) List group members</div> */}
  226. </button>
  227. );
  228. }) }
  229. <button type="button" className="btn btn-primary mt-2 mx-auto" onClick={() => setIsSelectGroupModalShown(false)}>{t('Done')}</button>
  230. </div>
  231. );
  232. }, [currentUser?.admin, groupListItemClickHandler, shouldFetch, t, groupGrantData, selectedGrant?.userRelatedGrantedGroups]);
  233. const renderModalCloseButton = useCallback(() => {
  234. return (
  235. <button
  236. type="button"
  237. className="btn border-0 text-muted"
  238. onClick={() => setIsSelectGroupModalShown(false)}
  239. >
  240. <span className="material-symbols-outlined">close</span>
  241. </button>
  242. );
  243. }, [setIsSelectGroupModalShown]);
  244. return (
  245. <>
  246. { renderGrantSelector() }
  247. {/* render modal */}
  248. { !disabled && currentUser != null && (
  249. <Modal
  250. isOpen={isSelectGroupModalShown}
  251. toggle={() => setIsSelectGroupModalShown(false)}
  252. centered
  253. >
  254. <ModalHeader tag="p" toggle={() => setIsSelectGroupModalShown(false)} className="fs-5 text-muted fw-bold pb-2" close={renderModalCloseButton()}>
  255. {t('user_group.select_group')}
  256. </ModalHeader>
  257. <ModalBody>
  258. {renderSelectGroupModalContent()}
  259. </ModalBody>
  260. </Modal>
  261. ) }
  262. </>
  263. );
  264. };