PageContainer.js 15 KB

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