PageContainer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import { pagePathUtils } from '@growi/core';
  2. import * as entities from 'entities';
  3. import * as toastr from 'toastr';
  4. import { Container } from 'unstated';
  5. import { EditorMode } from '~/stores/ui';
  6. import loggerFactory from '~/utils/logger';
  7. import { toastError } from '../util/apiNotification';
  8. import { apiPost } from '../util/apiv1-client';
  9. import { apiv3Post } from '../util/apiv3-client';
  10. import {
  11. DetachCodeBlockInterceptor,
  12. RestoreCodeBlockInterceptor,
  13. } from '../util/interceptor/detach-code-blocks';
  14. import {
  15. DrawioInterceptor,
  16. } from '../util/interceptor/drawio-interceptor';
  17. const { isTrashPage } = pagePathUtils;
  18. const logger = loggerFactory('growi:services:PageContainer');
  19. /**
  20. * Service container related to Page
  21. * @extends {Container} unstated Container
  22. */
  23. export default class PageContainer extends Container {
  24. constructor(appContainer) {
  25. super();
  26. this.appContainer = appContainer;
  27. this.appContainer.registerContainer(this);
  28. this.state = {};
  29. const mainContent = document.querySelector('#content-main');
  30. if (mainContent == null) {
  31. logger.debug('#content-main element is not exists');
  32. return;
  33. }
  34. const revisionId = mainContent.getAttribute('data-page-revision-id');
  35. const path = decodeURI(mainContent.getAttribute('data-path'));
  36. this.state = {
  37. // local page data
  38. markdown: null, // will be initialized after initStateMarkdown()
  39. pageId: mainContent.getAttribute('data-page-id'),
  40. revisionId,
  41. revisionCreatedAt: +mainContent.getAttribute('data-page-revision-created'),
  42. path,
  43. tocHtml: '',
  44. createdAt: mainContent.getAttribute('data-page-created-at'),
  45. // please use useCurrentUpdatedAt instead
  46. updatedAt: mainContent.getAttribute('data-page-updated-at'),
  47. deletedAt: mainContent.getAttribute('data-page-deleted-at') || null,
  48. isUserPage: JSON.parse(mainContent.getAttribute('data-page-user')) != null,
  49. isTrashPage: isTrashPage(path),
  50. isDeleted: JSON.parse(mainContent.getAttribute('data-page-is-deleted')),
  51. isNotCreatable: JSON.parse(mainContent.getAttribute('data-page-is-not-creatable')),
  52. isPageExist: mainContent.getAttribute('data-page-id') != null,
  53. pageUser: JSON.parse(mainContent.getAttribute('data-page-user')),
  54. tags: null,
  55. hasChildren: JSON.parse(mainContent.getAttribute('data-page-has-children')),
  56. templateTagData: mainContent.getAttribute('data-template-tags') || null,
  57. shareLinksNumber: mainContent.getAttribute('data-share-links-number'),
  58. shareLinkId: JSON.parse(mainContent.getAttribute('data-share-link-id') || null),
  59. // latest(on remote) information
  60. remoteRevisionId: revisionId,
  61. remoteRevisionBody: null,
  62. remoteRevisionUpdateAt: null,
  63. revisionIdHackmdSynced: mainContent.getAttribute('data-page-revision-id-hackmd-synced') || null,
  64. lastUpdateUsername: mainContent.getAttribute('data-page-last-update-username') || null,
  65. deleteUsername: mainContent.getAttribute('data-page-delete-username') || null,
  66. pageIdOnHackmd: mainContent.getAttribute('data-page-id-on-hackmd') || null,
  67. hasDraftOnHackmd: !!mainContent.getAttribute('data-page-has-draft-on-hackmd'),
  68. isHackmdDraftUpdatingInRealtime: false,
  69. isConflictDiffModalOpen: false,
  70. };
  71. // parse creator, lastUpdateUser and revisionAuthor
  72. try {
  73. this.state.creator = JSON.parse(mainContent.getAttribute('data-page-creator'));
  74. }
  75. catch (e) {
  76. logger.warn('The data of \'data-page-creator\' is invalid', e);
  77. }
  78. try {
  79. this.state.revisionAuthor = JSON.parse(mainContent.getAttribute('data-page-revision-author'));
  80. this.state.lastUpdateUser = JSON.parse(mainContent.getAttribute('data-page-revision-author'));
  81. }
  82. catch (e) {
  83. logger.warn('The data of \'data-page-revision-author\' is invalid', e);
  84. }
  85. const { interceptorManager } = this.appContainer;
  86. interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(appContainer), 10); // process as soon as possible
  87. interceptorManager.addInterceptor(new DrawioInterceptor(appContainer), 20);
  88. interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(appContainer), 900); // process as late as possible
  89. this.initStateMarkdown();
  90. this.setTocHtml = this.setTocHtml.bind(this);
  91. this.save = this.save.bind(this);
  92. this.emitJoinPageRoomRequest = this.emitJoinPageRoomRequest.bind(this);
  93. this.emitJoinPageRoomRequest();
  94. this.addWebSocketEventHandlers = this.addWebSocketEventHandlers.bind(this);
  95. this.addWebSocketEventHandlers();
  96. const unlinkPageButton = document.getElementById('unlink-page-button');
  97. if (unlinkPageButton != null) {
  98. unlinkPageButton.addEventListener('click', async() => {
  99. try {
  100. const res = await apiPost('/pages.unlink', { path });
  101. window.location.href = encodeURI(`${res.path}?unlinked=true`);
  102. }
  103. catch (err) {
  104. toastError(err);
  105. }
  106. });
  107. }
  108. }
  109. /**
  110. * Workaround for the mangling in production build to break constructor.name
  111. */
  112. static getClassName() {
  113. return 'PageContainer';
  114. }
  115. /**
  116. * whether to Empty Trash Page
  117. * not displayed when guest user and not on trash page
  118. */
  119. get isAbleToShowEmptyTrashButton() {
  120. const { currentUser } = this.appContainer;
  121. const { path, hasChildren } = this.state;
  122. return (currentUser != null && currentUser.admin && path === '/trash' && hasChildren);
  123. }
  124. /**
  125. * whether to display trash management buttons
  126. * ex.) undo, delete completly
  127. * not displayed when guest user
  128. */
  129. get isAbleToShowTrashPageManagementButtons() {
  130. const { currentUser } = this.appContainer;
  131. const { isDeleted } = this.state;
  132. return (isDeleted && currentUser != null);
  133. }
  134. /**
  135. * initialize state for markdown data
  136. */
  137. initStateMarkdown() {
  138. let pageContent = '';
  139. const rawText = document.getElementById('raw-text-original');
  140. if (rawText) {
  141. pageContent = rawText.innerHTML;
  142. }
  143. const markdown = entities.decodeHTML(pageContent);
  144. this.state.markdown = markdown;
  145. }
  146. setLatestRemotePageData(s2cMessagePageUpdated) {
  147. const newState = {
  148. remoteRevisionId: s2cMessagePageUpdated.revisionId,
  149. remoteRevisionBody: s2cMessagePageUpdated.revisionBody,
  150. remoteRevisionUpdateAt: s2cMessagePageUpdated.revisionUpdateAt,
  151. revisionIdHackmdSynced: s2cMessagePageUpdated.revisionIdHackmdSynced,
  152. // TODO // TODO remove lastUpdateUsername and refactor parts that lastUpdateUsername is used
  153. lastUpdateUsername: s2cMessagePageUpdated.lastUpdateUsername,
  154. lastUpdateUser: s2cMessagePageUpdated.remoteLastUpdateUser,
  155. };
  156. if (s2cMessagePageUpdated.hasDraftOnHackmd != null) {
  157. newState.hasDraftOnHackmd = s2cMessagePageUpdated.hasDraftOnHackmd;
  158. }
  159. this.setState(newState);
  160. }
  161. async setTocHtml(tocHtml) {
  162. if (this.state.tocHtml !== tocHtml) {
  163. this.setState({ tocHtml });
  164. }
  165. }
  166. /**
  167. * save success handler
  168. * @param {object} page Page instance
  169. * @param {Array[Tag]} tags Array of Tag
  170. * @param {object} revision Revision instance
  171. */
  172. updateStateAfterSave(page, tags, revision, editorMode) {
  173. // update state of PageContainer
  174. const newState = {
  175. pageId: page._id,
  176. revisionId: revision._id,
  177. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  178. remoteRevisionId: revision._id,
  179. revisionAuthor: revision.author,
  180. revisionIdHackmdSynced: page.revisionHackmdSynced,
  181. hasDraftOnHackmd: page.hasDraftOnHackmd,
  182. markdown: revision.body,
  183. createdAt: page.createdAt,
  184. updatedAt: page.updatedAt,
  185. };
  186. if (tags != null) {
  187. newState.tags = tags;
  188. }
  189. this.setState(newState);
  190. // PageEditor component
  191. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  192. if (pageEditor != null) {
  193. if (editorMode !== EditorMode.Editor) {
  194. pageEditor.updateEditorValue(newState.markdown);
  195. }
  196. }
  197. // PageEditorByHackmd component
  198. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  199. if (pageEditorByHackmd != null) {
  200. // reset
  201. if (editorMode !== EditorMode.HackMD) {
  202. pageEditorByHackmd.reset();
  203. }
  204. }
  205. }
  206. /**
  207. * update page meta data
  208. * @param {object} page Page instance
  209. * @param {object} revision Revision instance
  210. * @param {String[]} tags Array of Tag
  211. */
  212. updatePageMetaData(page, revision, tags) {
  213. const newState = {
  214. revisionId: revision._id,
  215. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  216. remoteRevisionId: revision._id,
  217. revisionAuthor: revision.author,
  218. revisionIdHackmdSynced: page.revisionHackmdSynced,
  219. hasDraftOnHackmd: page.hasDraftOnHackmd,
  220. updatedAt: page.updatedAt,
  221. };
  222. if (tags != null) {
  223. newState.tags = tags;
  224. }
  225. this.setState(newState);
  226. }
  227. /**
  228. * Save page
  229. * @param {string} markdown
  230. * @param {object} optionsToSave
  231. * @return {object} { page: Page, tags: Tag[] }
  232. */
  233. async save(markdown, editorMode, optionsToSave = {}) {
  234. const { pageId, path } = this.state;
  235. let { revisionId } = this.state;
  236. const options = Object.assign({}, optionsToSave);
  237. if (editorMode === 'hackmd') {
  238. // set option to sync
  239. options.isSyncRevisionToHackmd = true;
  240. revisionId = this.state.revisionIdHackmdSynced;
  241. }
  242. let res;
  243. if (pageId == null) {
  244. res = await this.createPage(path, markdown, options);
  245. }
  246. else {
  247. res = await this.updatePage(pageId, revisionId, markdown, options);
  248. }
  249. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  250. return res;
  251. }
  252. async saveAndReload(optionsToSave, editorMode) {
  253. if (optionsToSave == null) {
  254. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  255. throw new Error(msg);
  256. }
  257. if (editorMode == null) {
  258. logger.warn('\'saveAndReload\' requires the \'editorMode\' param');
  259. return;
  260. }
  261. const { pageId, path } = this.state;
  262. let { revisionId } = this.state;
  263. const options = Object.assign({}, optionsToSave);
  264. let markdown;
  265. if (editorMode === 'hackmd') {
  266. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  267. markdown = await pageEditorByHackmd.getMarkdown();
  268. // set option to sync
  269. options.isSyncRevisionToHackmd = true;
  270. revisionId = this.state.revisionIdHackmdSynced;
  271. }
  272. else {
  273. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  274. markdown = pageEditor.getMarkdown();
  275. }
  276. let res;
  277. if (pageId == null) {
  278. res = await this.createPage(path, markdown, options);
  279. }
  280. else {
  281. res = await this.updatePage(pageId, revisionId, markdown, options);
  282. }
  283. const editorContainer = this.appContainer.getContainer('EditorContainer');
  284. editorContainer.clearDraft(path);
  285. window.location.href = path;
  286. return res;
  287. }
  288. async createPage(pagePath, markdown, tmpParams) {
  289. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  290. // clone
  291. const params = Object.assign(tmpParams, {
  292. path: pagePath,
  293. body: markdown,
  294. });
  295. const res = await apiv3Post('/pages/', params);
  296. const { page, tags, revision } = res.data;
  297. return { page, tags, revision };
  298. }
  299. async updatePage(pageId, revisionId, markdown, tmpParams) {
  300. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  301. // clone
  302. const params = Object.assign(tmpParams, {
  303. page_id: pageId,
  304. revision_id: revisionId,
  305. body: markdown,
  306. });
  307. const res = await apiPost('/pages.update', params);
  308. if (!res.ok) {
  309. throw new Error(res.error);
  310. }
  311. return res;
  312. }
  313. showSuccessToastr() {
  314. toastr.success(undefined, 'Saved successfully', {
  315. closeButton: true,
  316. progressBar: true,
  317. newestOnTop: false,
  318. showDuration: '100',
  319. hideDuration: '100',
  320. timeOut: '1200',
  321. extendedTimeOut: '150',
  322. });
  323. }
  324. showErrorToastr(error) {
  325. toastr.error(error.message, 'Error occured', {
  326. closeButton: true,
  327. progressBar: true,
  328. newestOnTop: false,
  329. showDuration: '100',
  330. hideDuration: '100',
  331. timeOut: '3000',
  332. });
  333. }
  334. // request to server so the client to join a room for each page
  335. emitJoinPageRoomRequest() {
  336. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  337. const socket = socketIoContainer.getSocket();
  338. socket.emit('join:page', { socketId: socket.id, pageId: this.state.pageId });
  339. }
  340. addWebSocketEventHandlers() {
  341. // eslint-disable-next-line @typescript-eslint/no-this-alias
  342. const pageContainer = this;
  343. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  344. const socket = socketIoContainer.getSocket();
  345. socket.on('page:create', (data) => {
  346. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  347. // update remote page data
  348. const { s2cMessagePageUpdated } = data;
  349. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  350. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  351. }
  352. });
  353. socket.on('page:update', (data) => {
  354. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  355. // update remote page data
  356. const { s2cMessagePageUpdated } = data;
  357. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  358. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  359. }
  360. });
  361. socket.on('page:delete', (data) => {
  362. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  363. // update remote page data
  364. const { s2cMessagePageUpdated } = data;
  365. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  366. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  367. }
  368. });
  369. socket.on('page:editingWithHackmd', (data) => {
  370. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  371. // update isHackmdDraftUpdatingInRealtime
  372. const { s2cMessagePageUpdated } = data;
  373. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  374. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  375. }
  376. });
  377. }
  378. /* TODO GW-325 */
  379. retrieveMyBookmarkList() {
  380. }
  381. async resolveConflict(markdown, editorMode) {
  382. const { pageId, remoteRevisionId, path } = this.state;
  383. const editorContainer = this.appContainer.getContainer('EditorContainer');
  384. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  385. const options = editorContainer.getCurrentOptionsToSave();
  386. const optionsToSave = Object.assign({}, options);
  387. const res = await this.updatePage(pageId, remoteRevisionId, markdown, optionsToSave);
  388. editorContainer.clearDraft(path);
  389. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  390. if (pageEditor != null) {
  391. pageEditor.updateEditorValue(markdown);
  392. }
  393. editorContainer.setState({ tags: res.tags });
  394. return res;
  395. }
  396. }