PageContainer.js 15 KB

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