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