PageContainer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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 display reaction buttons
  115. * ex.) like, bookmark
  116. */
  117. get isAbleToShowPageReactionButtons() {
  118. const { isTrashPage, isPageExist } = this.state;
  119. const { isSharedUser } = this.appContainer;
  120. return (!isTrashPage && isPageExist && !isSharedUser);
  121. }
  122. /**
  123. * whether to display tag labels
  124. */
  125. get isAbleToShowTagLabel() {
  126. const { isUserPage } = this.state;
  127. const { isSharedUser } = this.appContainer;
  128. return (!isUserPage && !isSharedUser);
  129. }
  130. /**
  131. * whether to display page management
  132. * ex.) duplicate, rename
  133. */
  134. get isAbleToShowPageManagement() {
  135. const { isPageExist, isTrashPage } = this.state;
  136. const { isSharedUser } = this.appContainer;
  137. return (isPageExist && !isTrashPage && !isSharedUser);
  138. }
  139. /**
  140. * whether to display pageEditorModeManager
  141. * ex.) view, edit, hackmd
  142. */
  143. get isAbleToShowPageEditorModeManager() {
  144. const { isNotCreatable, isTrashPage } = this.state;
  145. const { isSharedUser } = this.appContainer;
  146. return (!isNotCreatable && !isTrashPage && !isSharedUser);
  147. }
  148. /**
  149. * whether to display pageAuthors
  150. * ex.) creator, lastUpdateUser
  151. */
  152. get isAbleToShowPageAuthors() {
  153. const { isPageExist, isUserPage } = this.state;
  154. return (isPageExist && !isUserPage);
  155. }
  156. /**
  157. * whether to like button
  158. * not displayed on user page
  159. */
  160. get isAbleToShowLikeButtons() {
  161. const { isUserPage } = this.state;
  162. const { isSharedUser } = this.appContainer;
  163. return (!isUserPage && !isSharedUser);
  164. }
  165. /**
  166. * whether to Empty Trash Page
  167. * not displayed when guest user and not on trash page
  168. */
  169. get isAbleToShowEmptyTrashButton() {
  170. const { currentUser } = this.appContainer;
  171. const { path, hasChildren } = this.state;
  172. return (currentUser != null && currentUser.admin && path === '/trash' && hasChildren);
  173. }
  174. /**
  175. * whether to display trash management buttons
  176. * ex.) undo, delete completly
  177. * not displayed when guest user
  178. */
  179. get isAbleToShowTrashPageManagementButtons() {
  180. const { currentUser } = this.appContainer;
  181. const { isDeleted } = this.state;
  182. return (isDeleted && currentUser != null);
  183. }
  184. /**
  185. * initialize state for markdown data
  186. */
  187. initStateMarkdown() {
  188. let pageContent = '';
  189. const rawText = document.getElementById('raw-text-original');
  190. if (rawText) {
  191. pageContent = rawText.innerHTML;
  192. }
  193. const markdown = entities.decodeHTML(pageContent);
  194. this.state.markdown = markdown;
  195. }
  196. setLatestRemotePageData(s2cMessagePageUpdated) {
  197. const newState = {
  198. remoteRevisionId: s2cMessagePageUpdated.revisionId,
  199. remoteRevisionBody: s2cMessagePageUpdated.revisionBody,
  200. remoteRevisionUpdateAt: s2cMessagePageUpdated.revisionUpdateAt,
  201. revisionIdHackmdSynced: s2cMessagePageUpdated.revisionIdHackmdSynced,
  202. // TODO // TODO remove lastUpdateUsername and refactor parts that lastUpdateUsername is used
  203. lastUpdateUsername: s2cMessagePageUpdated.lastUpdateUsername,
  204. lastUpdateUser: s2cMessagePageUpdated.remoteLastUpdateUser,
  205. };
  206. if (s2cMessagePageUpdated.hasDraftOnHackmd != null) {
  207. newState.hasDraftOnHackmd = s2cMessagePageUpdated.hasDraftOnHackmd;
  208. }
  209. this.setState(newState);
  210. }
  211. setTocHtml(tocHtml) {
  212. if (this.state.tocHtml !== tocHtml) {
  213. this.setState({ tocHtml });
  214. }
  215. }
  216. /**
  217. * save success handler
  218. * @param {object} page Page instance
  219. * @param {Array[Tag]} tags Array of Tag
  220. * @param {object} revision Revision instance
  221. */
  222. updateStateAfterSave(page, tags, revision, editorMode) {
  223. // update state of PageContainer
  224. const newState = {
  225. pageId: page._id,
  226. revisionId: revision._id,
  227. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  228. remoteRevisionId: revision._id,
  229. revisionAuthor: revision.author,
  230. revisionIdHackmdSynced: page.revisionHackmdSynced,
  231. hasDraftOnHackmd: page.hasDraftOnHackmd,
  232. markdown: revision.body,
  233. createdAt: page.createdAt,
  234. updatedAt: page.updatedAt,
  235. };
  236. if (tags != null) {
  237. newState.tags = tags;
  238. }
  239. this.setState(newState);
  240. // PageEditor component
  241. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  242. if (pageEditor != null) {
  243. if (editorMode !== EditorMode.Editor) {
  244. pageEditor.updateEditorValue(newState.markdown);
  245. }
  246. }
  247. // PageEditorByHackmd component
  248. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  249. if (pageEditorByHackmd != null) {
  250. // reset
  251. if (editorMode !== EditorMode.HackMD) {
  252. pageEditorByHackmd.reset();
  253. }
  254. }
  255. }
  256. /**
  257. * update page meta data
  258. * @param {object} page Page instance
  259. * @param {object} revision Revision instance
  260. * @param {String[]} tags Array of Tag
  261. */
  262. updatePageMetaData(page, revision, tags) {
  263. const newState = {
  264. revisionId: revision._id,
  265. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  266. remoteRevisionId: revision._id,
  267. revisionAuthor: revision.author,
  268. revisionIdHackmdSynced: page.revisionHackmdSynced,
  269. hasDraftOnHackmd: page.hasDraftOnHackmd,
  270. updatedAt: page.updatedAt,
  271. };
  272. if (tags != null) {
  273. newState.tags = tags;
  274. }
  275. this.setState(newState);
  276. }
  277. /**
  278. * Save page
  279. * @param {string} markdown
  280. * @param {object} optionsToSave
  281. * @return {object} { page: Page, tags: Tag[] }
  282. */
  283. async save(markdown, editorMode, optionsToSave = {}) {
  284. const { pageId, path } = this.state;
  285. let { revisionId } = this.state;
  286. const options = Object.assign({}, optionsToSave);
  287. if (editorMode === 'hackmd') {
  288. // set option to sync
  289. options.isSyncRevisionToHackmd = true;
  290. revisionId = this.state.revisionIdHackmdSynced;
  291. }
  292. let res;
  293. if (pageId == null) {
  294. res = await this.createPage(path, markdown, options);
  295. }
  296. else {
  297. res = await this.updatePage(pageId, revisionId, markdown, options);
  298. }
  299. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  300. return res;
  301. }
  302. async saveAndReload(optionsToSave, editorMode) {
  303. if (optionsToSave == null) {
  304. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  305. throw new Error(msg);
  306. }
  307. if (editorMode == null) {
  308. logger.warn('\'saveAndReload\' requires the \'editorMode\' param');
  309. return;
  310. }
  311. const { pageId, path } = this.state;
  312. let { revisionId } = this.state;
  313. const options = Object.assign({}, optionsToSave);
  314. let markdown;
  315. if (editorMode === 'hackmd') {
  316. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  317. markdown = await pageEditorByHackmd.getMarkdown();
  318. // set option to sync
  319. options.isSyncRevisionToHackmd = true;
  320. revisionId = this.state.revisionIdHackmdSynced;
  321. }
  322. else {
  323. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  324. markdown = pageEditor.getMarkdown();
  325. }
  326. let res;
  327. if (pageId == null) {
  328. res = await this.createPage(path, markdown, options);
  329. }
  330. else {
  331. res = await this.updatePage(pageId, revisionId, markdown, options);
  332. }
  333. const editorContainer = this.appContainer.getContainer('EditorContainer');
  334. editorContainer.clearDraft(path);
  335. window.location.href = path;
  336. return res;
  337. }
  338. async createPage(pagePath, markdown, tmpParams) {
  339. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  340. // clone
  341. const params = Object.assign(tmpParams, {
  342. path: pagePath,
  343. body: markdown,
  344. });
  345. const res = await this.appContainer.apiv3Post('/pages/', params);
  346. const { page, tags, revision } = res.data;
  347. return { page, tags, revision };
  348. }
  349. async updatePage(pageId, revisionId, markdown, tmpParams) {
  350. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  351. // clone
  352. const params = Object.assign(tmpParams, {
  353. page_id: pageId,
  354. revision_id: revisionId,
  355. body: markdown,
  356. });
  357. const res = await this.appContainer.apiPost('/pages.update', params);
  358. if (!res.ok) {
  359. throw new Error(res.error);
  360. }
  361. return res;
  362. }
  363. showSuccessToastr() {
  364. toastr.success(undefined, 'Saved successfully', {
  365. closeButton: true,
  366. progressBar: true,
  367. newestOnTop: false,
  368. showDuration: '100',
  369. hideDuration: '100',
  370. timeOut: '1200',
  371. extendedTimeOut: '150',
  372. });
  373. }
  374. showErrorToastr(error) {
  375. toastr.error(error.message, 'Error occured', {
  376. closeButton: true,
  377. progressBar: true,
  378. newestOnTop: false,
  379. showDuration: '100',
  380. hideDuration: '100',
  381. timeOut: '3000',
  382. });
  383. }
  384. // request to server so the client to join a room for each page
  385. emitJoinPageRoomRequest() {
  386. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  387. const socket = socketIoContainer.getSocket();
  388. socket.emit('join:page', { socketId: socket.id, pageId: this.state.pageId });
  389. }
  390. addWebSocketEventHandlers() {
  391. // eslint-disable-next-line @typescript-eslint/no-this-alias
  392. const pageContainer = this;
  393. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  394. const socket = socketIoContainer.getSocket();
  395. socket.on('page:create', (data) => {
  396. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  397. // update remote page data
  398. const { s2cMessagePageUpdated } = data;
  399. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  400. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  401. }
  402. });
  403. socket.on('page:update', (data) => {
  404. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  405. // update remote page data
  406. const { s2cMessagePageUpdated } = data;
  407. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  408. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  409. }
  410. });
  411. socket.on('page:delete', (data) => {
  412. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  413. // update remote page data
  414. const { s2cMessagePageUpdated } = data;
  415. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  416. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  417. }
  418. });
  419. socket.on('page:editingWithHackmd', (data) => {
  420. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  421. // update isHackmdDraftUpdatingInRealtime
  422. const { s2cMessagePageUpdated } = data;
  423. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  424. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  425. }
  426. });
  427. }
  428. /* TODO GW-325 */
  429. retrieveMyBookmarkList() {
  430. }
  431. async resolveConflict(markdown, editorMode) {
  432. const { pageId, remoteRevisionId, path } = this.state;
  433. const editorContainer = this.appContainer.getContainer('EditorContainer');
  434. const options = editorContainer.getCurrentOptionsToSave();
  435. const optionsToSave = Object.assign({}, options);
  436. const res = await this.updatePage(pageId, remoteRevisionId, markdown, optionsToSave);
  437. editorContainer.clearDraft(path);
  438. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  439. editorContainer.setState({ tags: res.tags });
  440. return res;
  441. }
  442. }