PageContainer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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 } = this.appContainer;
  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. window.globalEmitter.emit('updateEditorValue', newState.markdown);
  186. }
  187. // PageEditorByHackmd component
  188. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  189. if (pageEditorByHackmd != null) {
  190. // reset
  191. if (editorMode !== EditorMode.HackMD) {
  192. pageEditorByHackmd.reset();
  193. }
  194. }
  195. }
  196. /**
  197. * update page meta data
  198. * @param {object} page Page instance
  199. * @param {object} revision Revision instance
  200. * @param {String[]} tags Array of Tag
  201. */
  202. updatePageMetaData(page, revision, tags) {
  203. const newState = {
  204. revisionId: revision._id,
  205. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  206. remoteRevisionId: revision._id,
  207. revisionAuthor: revision.author,
  208. revisionIdHackmdSynced: page.revisionHackmdSynced,
  209. hasDraftOnHackmd: page.hasDraftOnHackmd,
  210. updatedAt: page.updatedAt,
  211. };
  212. if (tags != null) {
  213. newState.tags = tags;
  214. }
  215. this.setState(newState);
  216. }
  217. /**
  218. * Save page
  219. * @param {string} markdown
  220. * @param {object} optionsToSave
  221. * @return {object} { page: Page, tags: Tag[] }
  222. */
  223. async save(markdown, editorMode, optionsToSave = {}) {
  224. const { pageId, path } = this.state;
  225. let { revisionId } = this.state;
  226. const options = Object.assign({}, optionsToSave);
  227. if (editorMode === EditorMode.HackMD) {
  228. // set option to sync
  229. options.isSyncRevisionToHackmd = true;
  230. revisionId = this.state.revisionIdHackmdSynced;
  231. }
  232. let res;
  233. if (pageId == null) {
  234. res = await this.createPage(path, markdown, options);
  235. }
  236. else {
  237. res = await this.updatePage(pageId, revisionId, markdown, options);
  238. }
  239. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  240. return res;
  241. }
  242. async saveAndReload(optionsToSave, editorMode) {
  243. if (optionsToSave == null) {
  244. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  245. throw new Error(msg);
  246. }
  247. if (editorMode == null) {
  248. logger.warn('\'saveAndReload\' requires the \'editorMode\' param');
  249. return;
  250. }
  251. const { pageId, path } = this.state;
  252. let { revisionId } = this.state;
  253. const options = Object.assign({}, optionsToSave);
  254. let markdown;
  255. if (editorMode === EditorMode.HackMD) {
  256. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  257. markdown = await pageEditorByHackmd.getMarkdown();
  258. // set option to sync
  259. options.isSyncRevisionToHackmd = true;
  260. revisionId = this.state.revisionIdHackmdSynced;
  261. }
  262. else {
  263. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  264. markdown = pageEditor.getMarkdown();
  265. }
  266. let res;
  267. if (pageId == null) {
  268. res = await this.createPage(path, markdown, options);
  269. }
  270. else {
  271. res = await this.updatePage(pageId, revisionId, markdown, options);
  272. }
  273. const editorContainer = this.appContainer.getContainer('EditorContainer');
  274. editorContainer.clearDraft(path);
  275. window.location.href = path;
  276. return res;
  277. }
  278. async createPage(pagePath, markdown, tmpParams) {
  279. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  280. // clone
  281. const params = Object.assign(tmpParams, {
  282. path: pagePath,
  283. body: markdown,
  284. });
  285. const res = await apiv3Post('/pages/', params);
  286. const { page, tags, revision } = res.data;
  287. return { page, tags, revision };
  288. }
  289. async updatePage(pageId, revisionId, markdown, tmpParams) {
  290. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  291. // clone
  292. const params = Object.assign(tmpParams, {
  293. page_id: pageId,
  294. revision_id: revisionId,
  295. body: markdown,
  296. });
  297. const res = await apiPost('/pages.update', params);
  298. if (!res.ok) {
  299. throw new Error(res.error);
  300. }
  301. return res;
  302. }
  303. showSuccessToastr() {
  304. toastr.success(undefined, 'Saved successfully', {
  305. closeButton: true,
  306. progressBar: true,
  307. newestOnTop: false,
  308. showDuration: '100',
  309. hideDuration: '100',
  310. timeOut: '1200',
  311. extendedTimeOut: '150',
  312. });
  313. }
  314. showErrorToastr(error) {
  315. toastr.error(error.message, 'Error occured', {
  316. closeButton: true,
  317. progressBar: true,
  318. newestOnTop: false,
  319. showDuration: '100',
  320. hideDuration: '100',
  321. timeOut: '3000',
  322. });
  323. }
  324. // request to server so the client to join a room for each page
  325. emitJoinPageRoomRequest() {
  326. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  327. const socket = socketIoContainer.getSocket();
  328. socket.emit('join:page', { socketId: socket.id, pageId: this.state.pageId });
  329. }
  330. addWebSocketEventHandlers() {
  331. // eslint-disable-next-line @typescript-eslint/no-this-alias
  332. const pageContainer = this;
  333. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  334. const socket = socketIoContainer.getSocket();
  335. socket.on('page:create', (data) => {
  336. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  337. // update remote page data
  338. const { s2cMessagePageUpdated } = data;
  339. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  340. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  341. }
  342. });
  343. socket.on('page:update', (data) => {
  344. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  345. // update remote page data
  346. const { s2cMessagePageUpdated } = data;
  347. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  348. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  349. }
  350. });
  351. socket.on('page:delete', (data) => {
  352. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  353. // update remote page data
  354. const { s2cMessagePageUpdated } = data;
  355. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  356. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  357. }
  358. });
  359. socket.on('page:editingWithHackmd', (data) => {
  360. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  361. // update isHackmdDraftUpdatingInRealtime
  362. const { s2cMessagePageUpdated } = data;
  363. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  364. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  365. }
  366. });
  367. }
  368. /* TODO GW-325 */
  369. retrieveMyBookmarkList() {
  370. }
  371. async resolveConflict(markdown, editorMode) {
  372. const { pageId, remoteRevisionId, path } = this.state;
  373. const editorContainer = this.appContainer.getContainer('EditorContainer');
  374. const options = editorContainer.getCurrentOptionsToSave();
  375. const optionsToSave = Object.assign({}, options);
  376. const res = await this.updatePage(pageId, remoteRevisionId, markdown, optionsToSave);
  377. editorContainer.clearDraft(path);
  378. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  379. // Update PageEditor component
  380. if (editorMode !== EditorMode.Editor) {
  381. window.globalEmitter.emit('updateEditorValue', markdown);
  382. }
  383. editorContainer.setState({ tags: res.tags });
  384. return res;
  385. }
  386. }