PageContainer.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. * initialize state for markdown data
  115. */
  116. initStateMarkdown() {
  117. let pageContent = '';
  118. const rawText = document.getElementById('raw-text-original');
  119. if (rawText) {
  120. pageContent = rawText.innerHTML;
  121. }
  122. const markdown = entities.decodeHTML(pageContent);
  123. this.state.markdown = markdown;
  124. }
  125. setLatestRemotePageData(s2cMessagePageUpdated) {
  126. const newState = {
  127. remoteRevisionId: s2cMessagePageUpdated.revisionId,
  128. remoteRevisionBody: s2cMessagePageUpdated.revisionBody,
  129. remoteRevisionUpdateAt: s2cMessagePageUpdated.revisionUpdateAt,
  130. revisionIdHackmdSynced: s2cMessagePageUpdated.revisionIdHackmdSynced,
  131. // TODO // TODO remove lastUpdateUsername and refactor parts that lastUpdateUsername is used
  132. lastUpdateUsername: s2cMessagePageUpdated.lastUpdateUsername,
  133. lastUpdateUser: s2cMessagePageUpdated.remoteLastUpdateUser,
  134. };
  135. if (s2cMessagePageUpdated.hasDraftOnHackmd != null) {
  136. newState.hasDraftOnHackmd = s2cMessagePageUpdated.hasDraftOnHackmd;
  137. }
  138. this.setState(newState);
  139. }
  140. /**
  141. * save success handler
  142. * @param {object} page Page instance
  143. * @param {Array[Tag]} tags Array of Tag
  144. * @param {object} revision Revision instance
  145. */
  146. updateStateAfterSave(page, tags, revision, editorMode) {
  147. // update state of PageContainer
  148. const newState = {
  149. pageId: page._id,
  150. revisionId: revision._id,
  151. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  152. remoteRevisionId: revision._id,
  153. revisionAuthor: revision.author,
  154. revisionIdHackmdSynced: page.revisionHackmdSynced,
  155. hasDraftOnHackmd: page.hasDraftOnHackmd,
  156. markdown: revision.body,
  157. createdAt: page.createdAt,
  158. updatedAt: page.updatedAt,
  159. };
  160. if (tags != null) {
  161. newState.tags = tags;
  162. }
  163. this.setState(newState);
  164. // Update PageEditor component
  165. if (editorMode !== EditorMode.Editor) {
  166. // eslint-disable-next-line no-undef
  167. globalEmitter.emit('updateEditorValue', newState.markdown);
  168. }
  169. // PageEditorByHackmd component
  170. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  171. if (pageEditorByHackmd != null) {
  172. // reset
  173. if (editorMode !== EditorMode.HackMD) {
  174. pageEditorByHackmd.reset();
  175. }
  176. }
  177. }
  178. /**
  179. * update page meta data
  180. * @param {object} page Page instance
  181. * @param {object} revision Revision instance
  182. * @param {String[]} tags Array of Tag
  183. */
  184. updatePageMetaData(page, revision, tags) {
  185. const newState = {
  186. revisionId: revision._id,
  187. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  188. remoteRevisionId: revision._id,
  189. revisionAuthor: revision.author,
  190. revisionIdHackmdSynced: page.revisionHackmdSynced,
  191. hasDraftOnHackmd: page.hasDraftOnHackmd,
  192. updatedAt: page.updatedAt,
  193. };
  194. if (tags != null) {
  195. newState.tags = tags;
  196. }
  197. this.setState(newState);
  198. }
  199. /**
  200. * Save page
  201. * @param {string} markdown
  202. * @param {object} optionsToSave
  203. * @return {object} { page: Page, tags: Tag[] }
  204. */
  205. async save(markdown, editorMode, optionsToSave = {}) {
  206. const { pageId, path } = this.state;
  207. let { revisionId } = this.state;
  208. const options = Object.assign({}, optionsToSave);
  209. if (editorMode === EditorMode.HackMD) {
  210. // set option to sync
  211. options.isSyncRevisionToHackmd = true;
  212. revisionId = this.state.revisionIdHackmdSynced;
  213. }
  214. let res;
  215. if (pageId == null) {
  216. res = await this.createPage(path, markdown, options);
  217. }
  218. else {
  219. res = await this.updatePage(pageId, revisionId, markdown, options);
  220. }
  221. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  222. return res;
  223. }
  224. async saveAndReload(optionsToSave, editorMode) {
  225. if (optionsToSave == null) {
  226. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  227. throw new Error(msg);
  228. }
  229. if (editorMode == null) {
  230. logger.warn('\'saveAndReload\' requires the \'editorMode\' param');
  231. return;
  232. }
  233. const { pageId, path } = this.state;
  234. let { revisionId } = this.state;
  235. const options = Object.assign({}, optionsToSave);
  236. let markdown;
  237. if (editorMode === EditorMode.HackMD) {
  238. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  239. markdown = await pageEditorByHackmd.getMarkdown();
  240. // set option to sync
  241. options.isSyncRevisionToHackmd = true;
  242. revisionId = this.state.revisionIdHackmdSynced;
  243. }
  244. else {
  245. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  246. markdown = pageEditor.getMarkdown();
  247. }
  248. let res;
  249. if (pageId == null) {
  250. res = await this.createPage(path, markdown, options);
  251. }
  252. else {
  253. res = await this.updatePage(pageId, revisionId, markdown, options);
  254. }
  255. const editorContainer = this.appContainer.getContainer('EditorContainer');
  256. editorContainer.clearDraft(path);
  257. window.location.href = path;
  258. return res;
  259. }
  260. async createPage(pagePath, markdown, tmpParams) {
  261. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  262. // clone
  263. const params = Object.assign(tmpParams, {
  264. path: pagePath,
  265. body: markdown,
  266. });
  267. const res = await apiv3Post('/pages/', params);
  268. const { page, tags, revision } = res.data;
  269. return { page, tags, revision };
  270. }
  271. async updatePage(pageId, revisionId, markdown, tmpParams) {
  272. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  273. // clone
  274. const params = Object.assign(tmpParams, {
  275. page_id: pageId,
  276. revision_id: revisionId,
  277. body: markdown,
  278. });
  279. const res = await apiPost('/pages.update', params);
  280. if (!res.ok) {
  281. throw new Error(res.error);
  282. }
  283. return res;
  284. }
  285. showSuccessToastr() {
  286. toastr.success(undefined, 'Saved successfully', {
  287. closeButton: true,
  288. progressBar: true,
  289. newestOnTop: false,
  290. showDuration: '100',
  291. hideDuration: '100',
  292. timeOut: '1200',
  293. extendedTimeOut: '150',
  294. });
  295. }
  296. showErrorToastr(error) {
  297. toastr.error(error.message, 'Error occured', {
  298. closeButton: true,
  299. progressBar: true,
  300. newestOnTop: false,
  301. showDuration: '100',
  302. hideDuration: '100',
  303. timeOut: '3000',
  304. });
  305. }
  306. // request to server so the client to join a room for each page
  307. emitJoinPageRoomRequest() {
  308. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  309. const socket = socketIoContainer.getSocket();
  310. socket.emit('join:page', { socketId: socket.id, pageId: this.state.pageId });
  311. }
  312. addWebSocketEventHandlers() {
  313. // eslint-disable-next-line @typescript-eslint/no-this-alias
  314. const pageContainer = this;
  315. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  316. const socket = socketIoContainer.getSocket();
  317. socket.on('page:create', (data) => {
  318. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  319. // update remote page data
  320. const { s2cMessagePageUpdated } = data;
  321. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  322. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  323. }
  324. });
  325. socket.on('page:update', (data) => {
  326. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  327. // update remote page data
  328. const { s2cMessagePageUpdated } = data;
  329. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  330. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  331. }
  332. });
  333. socket.on('page:delete', (data) => {
  334. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  335. // update remote page data
  336. const { s2cMessagePageUpdated } = data;
  337. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  338. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  339. }
  340. });
  341. socket.on('page:editingWithHackmd', (data) => {
  342. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  343. // update isHackmdDraftUpdatingInRealtime
  344. const { s2cMessagePageUpdated } = data;
  345. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  346. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  347. }
  348. });
  349. }
  350. /* TODO GW-325 */
  351. retrieveMyBookmarkList() {
  352. }
  353. async resolveConflict(markdown, editorMode) {
  354. const { pageId, remoteRevisionId, path } = this.state;
  355. const editorContainer = this.appContainer.getContainer('EditorContainer');
  356. const options = editorContainer.getCurrentOptionsToSave();
  357. const optionsToSave = Object.assign({}, options);
  358. const res = await this.updatePage(pageId, remoteRevisionId, markdown, optionsToSave);
  359. editorContainer.clearDraft(path);
  360. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  361. // Update PageEditor component
  362. if (editorMode !== EditorMode.Editor) {
  363. // eslint-disable-next-line no-undef
  364. globalEmitter.emit('updateEditorValue', markdown);
  365. }
  366. editorContainer.setState({ tags: res.tags });
  367. return res;
  368. }
  369. }