ConflictDiffModal.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import React, {
  2. useState, useEffect, useRef, useMemo, useCallback,
  3. } from 'react';
  4. import type { IRevisionOnConflict } from '@growi/core';
  5. import { UserPicture } from '@growi/ui/dist/components';
  6. import CodeMirror from 'codemirror/lib/codemirror';
  7. import { format, parseISO } from 'date-fns';
  8. import { useTranslation } from 'next-i18next';
  9. import {
  10. Modal, ModalHeader, ModalBody, ModalFooter,
  11. } from 'reactstrap';
  12. import { useSaveOrUpdate } from '~/client/services/page-operation';
  13. import { toastError, toastSuccess } from '~/client/util/toastr';
  14. import { OptionsToSave } from '~/interfaces/page-operation';
  15. import { useCurrentPathname, useCurrentUser } from '~/stores/context';
  16. import { useCurrentPagePath, useSWRxCurrentPage, useCurrentPageId } from '~/stores/page';
  17. import {
  18. useRemoteRevisionBody, useRemoteRevisionId, useRemoteRevisionLastUpdatedAt, useRemoteRevisionLastUpdateUser, useSetRemoteLatestPageData,
  19. } from '~/stores/remote-latest-page';
  20. import ExpandOrContractButton from '../ExpandOrContractButton';
  21. import { UncontrolledCodeMirror } from '../UncontrolledCodeMirror';
  22. require('codemirror/lib/codemirror.css');
  23. require('codemirror/addon/merge/merge');
  24. require('codemirror/addon/merge/merge.css');
  25. const DMP = require('diff_match_patch');
  26. Object.keys(DMP).forEach((key) => { window[key] = DMP[key] });
  27. type ConflictDiffModalProps = {
  28. isOpen?: boolean;
  29. onClose?: (() => void);
  30. markdownOnEdit: string;
  31. optionsToSave: OptionsToSave | undefined;
  32. afterResolvedHandler: () => void,
  33. };
  34. type ConflictDiffModalCoreProps = {
  35. isOpen?: boolean;
  36. onClose?: (() => void);
  37. optionsToSave: OptionsToSave | undefined;
  38. request: IRevisionOnConflictWithStringDate,
  39. origin: IRevisionOnConflictWithStringDate,
  40. latest: IRevisionOnConflictWithStringDate,
  41. afterResolvedHandler: () => void,
  42. };
  43. type IRevisionOnConflictWithStringDate = Omit<IRevisionOnConflict, 'createdAt'> & {
  44. createdAt: string
  45. }
  46. const ConflictDiffModalCore = (props: ConflictDiffModalCoreProps): JSX.Element => {
  47. const {
  48. onClose, request, origin, latest, optionsToSave, afterResolvedHandler,
  49. } = props;
  50. const { t } = useTranslation('');
  51. const [resolvedRevision, setResolvedRevision] = useState<string>('');
  52. const [isRevisionselected, setIsRevisionSelected] = useState<boolean>(false);
  53. const [isModalExpanded, setIsModalExpanded] = useState<boolean>(false);
  54. const [codeMirrorRef, setCodeMirrorRef] = useState<HTMLDivElement | null>(null);
  55. const { data: remoteRevisionId } = useRemoteRevisionId();
  56. const { setRemoteLatestPageData } = useSetRemoteLatestPageData();
  57. const { data: pageId } = useCurrentPageId();
  58. const { data: currentPagePath } = useCurrentPagePath();
  59. const { data: currentPathname } = useCurrentPathname();
  60. const saveOrUpdate = useSaveOrUpdate();
  61. const uncontrolledRef = useRef<CodeMirror>(null);
  62. useEffect(() => {
  63. if (codeMirrorRef != null) {
  64. CodeMirror.MergeView(codeMirrorRef, {
  65. value: origin.revisionBody,
  66. origLeft: request.revisionBody,
  67. origRight: latest.revisionBody,
  68. lineNumbers: true,
  69. collapseIdentical: true,
  70. showDifferences: true,
  71. highlightDifferences: true,
  72. connect: 'connect',
  73. readOnly: true,
  74. revertButtons: false,
  75. });
  76. }
  77. }, [codeMirrorRef, origin.revisionBody, request.revisionBody, latest.revisionBody]);
  78. const close = useCallback(() => {
  79. if (onClose != null) {
  80. onClose();
  81. }
  82. }, [onClose]);
  83. const onResolveConflict = useCallback(async() => {
  84. if (currentPathname == null) { return }
  85. // disable button after clicked
  86. setIsRevisionSelected(false);
  87. const codeMirrorVal = uncontrolledRef.current?.editor.doc.getValue();
  88. try {
  89. const { page } = await saveOrUpdate(
  90. codeMirrorVal,
  91. { pageId, path: currentPagePath || currentPathname, revisionId: remoteRevisionId },
  92. optionsToSave,
  93. );
  94. const remotePageData = {
  95. remoteRevisionId: page.revision._id,
  96. remoteRevisionBody: page.revision.body,
  97. remoteRevisionLastUpdateUser: page.lastUpdateUser,
  98. remoteRevisionLastUpdatedAt: page.updatedAt,
  99. revisionIdHackmdSynced: page.revisionIdHackmdSynced,
  100. hasDraftOnHackmd: page.hasDraftOnHackmd,
  101. };
  102. setRemoteLatestPageData(remotePageData);
  103. afterResolvedHandler();
  104. close();
  105. toastSuccess('Saved successfully');
  106. }
  107. catch (error) {
  108. toastError(`Error occured: ${error.message}`);
  109. }
  110. }, [afterResolvedHandler, close, currentPagePath, currentPathname, optionsToSave, pageId, remoteRevisionId, saveOrUpdate, setRemoteLatestPageData]);
  111. const resizeAndCloseButtons = useMemo(() => (
  112. <div className="d-flex flex-nowrap">
  113. <ExpandOrContractButton
  114. isWindowExpanded={isModalExpanded}
  115. expandWindow={() => setIsModalExpanded(true)}
  116. contractWindow={() => setIsModalExpanded(false)}
  117. />
  118. <button type="button" className="close text-white" onClick={close} aria-label="Close">
  119. <span aria-hidden="true">&times;</span>
  120. </button>
  121. </div>
  122. ), [isModalExpanded, close]);
  123. const isOpen = props.isOpen ?? false;
  124. return (
  125. <Modal
  126. isOpen={isOpen}
  127. toggle={close}
  128. backdrop="static"
  129. className={`${isModalExpanded ? ' grw-modal-expanded' : ''}`}
  130. size="xl"
  131. >
  132. <ModalHeader tag="h4" toggle={onClose} className="bg-primary text-light align-items-center py-3" close={resizeAndCloseButtons}>
  133. <i className="icon-fw icon-exclamation" />{t('modal_resolve_conflict.resolve_conflict')}
  134. </ModalHeader>
  135. <ModalBody className="mx-4 my-1">
  136. { isOpen
  137. && (
  138. <div className="row">
  139. <div className="col-12 text-center mt-2 mb-4">
  140. <h2 className="font-weight-bold">{t('modal_resolve_conflict.resolve_conflict_message')}</h2>
  141. </div>
  142. <div className="col-4">
  143. <h3 className="font-weight-bold my-2">{t('modal_resolve_conflict.requested_revision')}</h3>
  144. <div className="d-flex align-items-center my-3">
  145. <div>
  146. <UserPicture user={request.user} size="lg" noLink noTooltip />
  147. </div>
  148. <div className="ml-3 text-muted">
  149. <p className="my-0">updated by {request.user.username}</p>
  150. <p className="my-0">{request.createdAt}</p>
  151. </div>
  152. </div>
  153. </div>
  154. <div className="col-4">
  155. <h3 className="font-weight-bold my-2">{t('modal_resolve_conflict.origin_revision')}</h3>
  156. <div className="d-flex align-items-center my-3">
  157. <div>
  158. <UserPicture user={origin.user} size="lg" noLink noTooltip />
  159. </div>
  160. <div className="ml-3 text-muted">
  161. <p className="my-0">updated by {origin.user.username}</p>
  162. <p className="my-0">{origin.createdAt}</p>
  163. </div>
  164. </div>
  165. </div>
  166. <div className="col-4">
  167. <h3 className="font-weight-bold my-2">{t('modal_resolve_conflict.latest_revision')}</h3>
  168. <div className="d-flex align-items-center my-3">
  169. <div>
  170. <UserPicture user={latest.user} size="lg" noLink noTooltip />
  171. </div>
  172. <div className="ml-3 text-muted">
  173. <p className="my-0">updated by {latest.user.username}</p>
  174. <p className="my-0">{latest.createdAt}</p>
  175. </div>
  176. </div>
  177. </div>
  178. <div className="col-12" ref={(el) => { setCodeMirrorRef(el) }}></div>
  179. <div className="col-4">
  180. <div className="text-center my-4">
  181. <button
  182. type="button"
  183. className="btn btn-outline-primary"
  184. onClick={() => {
  185. setIsRevisionSelected(true);
  186. setResolvedRevision(request.revisionBody);
  187. }}
  188. >
  189. <i className="icon-fw icon-arrow-down-circle"></i>
  190. {t('modal_resolve_conflict.select_revision', { revision: 'mine' })}
  191. </button>
  192. </div>
  193. </div>
  194. <div className="col-4">
  195. <div className="text-center my-4">
  196. <button
  197. type="button"
  198. className="btn btn-outline-primary"
  199. onClick={() => {
  200. setIsRevisionSelected(true);
  201. setResolvedRevision(origin.revisionBody);
  202. }}
  203. >
  204. <i className="icon-fw icon-arrow-down-circle"></i>
  205. {t('modal_resolve_conflict.select_revision', { revision: 'origin' })}
  206. </button>
  207. </div>
  208. </div>
  209. <div className="col-4">
  210. <div className="text-center my-4">
  211. <button
  212. type="button"
  213. className="btn btn-outline-primary"
  214. onClick={() => {
  215. setIsRevisionSelected(true);
  216. setResolvedRevision(latest.revisionBody);
  217. }}
  218. >
  219. <i className="icon-fw icon-arrow-down-circle"></i>
  220. {t('modal_resolve_conflict.select_revision', { revision: 'theirs' })}
  221. </button>
  222. </div>
  223. </div>
  224. <div className="col-12">
  225. <div className="border border-dark">
  226. <h3 className="font-weight-bold my-2 mx-2">{t('modal_resolve_conflict.selected_editable_revision')}</h3>
  227. <UncontrolledCodeMirror
  228. ref={uncontrolledRef}
  229. value={resolvedRevision}
  230. options={{
  231. placeholder: t('modal_resolve_conflict.resolve_conflict_message'),
  232. }}
  233. />
  234. </div>
  235. </div>
  236. </div>
  237. )}
  238. </ModalBody>
  239. <ModalFooter>
  240. <button
  241. type="button"
  242. className="btn btn-outline-secondary"
  243. onClick={onClose}
  244. >
  245. {t('Cancel')}
  246. </button>
  247. <button
  248. type="button"
  249. className="btn btn-primary ml-3"
  250. onClick={onResolveConflict}
  251. disabled={!isRevisionselected}
  252. >
  253. {t('modal_resolve_conflict.resolve_and_save')}
  254. </button>
  255. </ModalFooter>
  256. </Modal>
  257. );
  258. };
  259. export const ConflictDiffModal = (props: ConflictDiffModalProps): JSX.Element => {
  260. const {
  261. isOpen, onClose, optionsToSave, afterResolvedHandler,
  262. } = props;
  263. const { data: currentUser } = useCurrentUser();
  264. // state for current page
  265. const { data: currentPage } = useSWRxCurrentPage();
  266. // state for latest page
  267. const { data: remoteRevisionId } = useRemoteRevisionId();
  268. const { data: remoteRevisionBody } = useRemoteRevisionBody();
  269. const { data: remoteRevisionLastUpdateUser } = useRemoteRevisionLastUpdateUser();
  270. const { data: remoteRevisionLastUpdatedAt } = useRemoteRevisionLastUpdatedAt();
  271. const currentTime: Date = new Date();
  272. const isRemotePageDataInappropriate = remoteRevisionId == null || remoteRevisionBody == null || remoteRevisionLastUpdateUser == null;
  273. if (!isOpen || currentUser == null || currentPage == null || isRemotePageDataInappropriate) {
  274. return <></>;
  275. }
  276. const currentPageCreatedAtFixed = typeof currentPage.updatedAt === 'string'
  277. ? parseISO(currentPage.updatedAt)
  278. : currentPage.updatedAt;
  279. const request: IRevisionOnConflictWithStringDate = {
  280. revisionId: '',
  281. revisionBody: props.markdownOnEdit,
  282. createdAt: format(currentTime, 'yyyy/MM/dd HH:mm:ss'),
  283. user: currentUser,
  284. };
  285. const origin: IRevisionOnConflictWithStringDate = {
  286. revisionId: currentPage?.revision._id,
  287. revisionBody: currentPage?.revision.body,
  288. createdAt: format(currentPageCreatedAtFixed, 'yyyy/MM/dd HH:mm:ss'),
  289. user: currentPage?.lastUpdateUser,
  290. };
  291. const latest: IRevisionOnConflictWithStringDate = {
  292. revisionId: remoteRevisionId,
  293. revisionBody: remoteRevisionBody,
  294. createdAt: format(new Date(remoteRevisionLastUpdatedAt || currentTime.toString()), 'yyyy/MM/dd HH:mm:ss'),
  295. user: remoteRevisionLastUpdateUser,
  296. };
  297. const propsForCore = {
  298. isOpen,
  299. onClose,
  300. optionsToSave,
  301. request,
  302. origin,
  303. latest,
  304. afterResolvedHandler,
  305. };
  306. return <ConflictDiffModalCore {...propsForCore}/>;
  307. };