PageContainer.js 14 KB

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