PageContainer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 { toastError } from '../util/apiNotification';
  7. import {
  8. DetachCodeBlockInterceptor,
  9. RestoreCodeBlockInterceptor,
  10. } from '../util/interceptor/detach-code-blocks';
  11. import {
  12. DrawioInterceptor,
  13. } from '../util/interceptor/drawio-interceptor';
  14. const { isTrashPage } = pagePathUtils;
  15. const logger = loggerFactory('growi:services:PageContainer');
  16. /**
  17. * Service container related to Page
  18. * @extends {Container} unstated Container
  19. */
  20. export default class PageContainer extends Container {
  21. constructor(appContainer) {
  22. super();
  23. this.appContainer = appContainer;
  24. this.appContainer.registerContainer(this);
  25. this.state = {};
  26. const mainContent = document.querySelector('#content-main');
  27. if (mainContent == null) {
  28. logger.debug('#content-main element is not exists');
  29. return;
  30. }
  31. const revisionId = mainContent.getAttribute('data-page-revision-id');
  32. const path = decodeURI(mainContent.getAttribute('data-path'));
  33. this.state = {
  34. // local page data
  35. markdown: null, // will be initialized after initStateMarkdown()
  36. pageId: mainContent.getAttribute('data-page-id'),
  37. revisionId,
  38. revisionCreatedAt: +mainContent.getAttribute('data-page-revision-created'),
  39. path,
  40. tocHtml: '',
  41. isLiked: false,
  42. isBookmarked: false,
  43. seenUsers: [],
  44. seenUserIds: mainContent.getAttribute('data-page-ids-of-seen-users'),
  45. countOfSeenUsers: mainContent.getAttribute('data-page-count-of-seen-users'),
  46. likerUsers: [],
  47. sumOfLikers: 0,
  48. sumOfBookmarks: 0,
  49. createdAt: mainContent.getAttribute('data-page-created-at'),
  50. updatedAt: mainContent.getAttribute('data-page-updated-at'),
  51. deletedAt: mainContent.getAttribute('data-page-deleted-at') || null,
  52. isUserPage: JSON.parse(mainContent.getAttribute('data-page-user')) != null,
  53. isTrashPage: isTrashPage(path),
  54. isDeleted: JSON.parse(mainContent.getAttribute('data-page-is-deleted')),
  55. isDeletable: JSON.parse(mainContent.getAttribute('data-page-is-deletable')),
  56. isNotCreatable: JSON.parse(mainContent.getAttribute('data-page-is-not-creatable')),
  57. isAbleToDeleteCompletely: JSON.parse(mainContent.getAttribute('data-page-is-able-to-delete-completely')),
  58. isPageExist: mainContent.getAttribute('data-page-id') != null,
  59. pageUser: JSON.parse(mainContent.getAttribute('data-page-user')),
  60. tags: null,
  61. hasChildren: JSON.parse(mainContent.getAttribute('data-page-has-children')),
  62. templateTagData: mainContent.getAttribute('data-template-tags') || null,
  63. shareLinksNumber: mainContent.getAttribute('data-share-links-number'),
  64. shareLinkId: JSON.parse(mainContent.getAttribute('data-share-link-id') || null),
  65. // latest(on remote) information
  66. remoteRevisionId: revisionId,
  67. revisionIdHackmdSynced: mainContent.getAttribute('data-page-revision-id-hackmd-synced') || null,
  68. lastUpdateUsername: mainContent.getAttribute('data-page-last-update-username') || null,
  69. deleteUsername: mainContent.getAttribute('data-page-delete-username') || null,
  70. pageIdOnHackmd: mainContent.getAttribute('data-page-id-on-hackmd') || null,
  71. hasDraftOnHackmd: !!mainContent.getAttribute('data-page-has-draft-on-hackmd'),
  72. isHackmdDraftUpdatingInRealtime: false,
  73. };
  74. // parse creator, lastUpdateUser and revisionAuthor
  75. try {
  76. this.state.creator = JSON.parse(mainContent.getAttribute('data-page-creator'));
  77. }
  78. catch (e) {
  79. logger.warn('The data of \'data-page-creator\' is invalid', e);
  80. }
  81. try {
  82. this.state.revisionAuthor = JSON.parse(mainContent.getAttribute('data-page-revision-author'));
  83. }
  84. catch (e) {
  85. logger.warn('The data of \'data-page-revision-author\' is invalid', e);
  86. }
  87. const { interceptorManager } = this.appContainer;
  88. interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(appContainer), 10); // process as soon as possible
  89. interceptorManager.addInterceptor(new DrawioInterceptor(appContainer), 20);
  90. interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(appContainer), 900); // process as late as possible
  91. this.initStateMarkdown();
  92. this.checkAndUpdateImageUrlCached(this.state.likerUsers);
  93. const { isSharedUser } = this.appContainer;
  94. // see https://dev.growi.org/5fabddf8bbeb1a0048bcb9e9
  95. const isAbleToGetAttachedInformationAboutPages = this.state.isPageExist && !isSharedUser;
  96. if (isAbleToGetAttachedInformationAboutPages) {
  97. this.retrieveSeenUsers();
  98. this.retrieveLikeInfo();
  99. this.retrieveBookmarkInfo();
  100. }
  101. this.setTocHtml = this.setTocHtml.bind(this);
  102. this.save = this.save.bind(this);
  103. this.checkAndUpdateImageUrlCached = this.checkAndUpdateImageUrlCached.bind(this);
  104. this.emitJoinPageRoomRequest = this.emitJoinPageRoomRequest.bind(this);
  105. this.emitJoinPageRoomRequest();
  106. this.addWebSocketEventHandlers = this.addWebSocketEventHandlers.bind(this);
  107. this.addWebSocketEventHandlers();
  108. const unlinkPageButton = document.getElementById('unlink-page-button');
  109. if (unlinkPageButton != null) {
  110. unlinkPageButton.addEventListener('click', async() => {
  111. try {
  112. const res = await this.appContainer.apiPost('/pages.unlink', { path });
  113. window.location.href = encodeURI(`${res.path}?unlinked=true`);
  114. }
  115. catch (err) {
  116. toastError(err);
  117. }
  118. });
  119. }
  120. }
  121. /**
  122. * Workaround for the mangling in production build to break constructor.name
  123. */
  124. static getClassName() {
  125. return 'PageContainer';
  126. }
  127. get isAbleToOpenPageEditor() {
  128. const { isNotCreatable, isTrashPage } = this.state;
  129. const { isGuestUser } = this.appContainer;
  130. return (!isNotCreatable && !isTrashPage && !isGuestUser);
  131. }
  132. /**
  133. * whether to display reaction buttons
  134. * ex.) like, bookmark
  135. */
  136. get isAbleToShowPageReactionButtons() {
  137. const { isTrashPage, isPageExist } = this.state;
  138. const { isSharedUser } = this.appContainer;
  139. return (!isTrashPage && isPageExist && !isSharedUser);
  140. }
  141. /**
  142. * whether to display tag labels
  143. */
  144. get isAbleToShowTagLabel() {
  145. const { isUserPage } = this.state;
  146. const { isSharedUser } = this.appContainer;
  147. return (!isUserPage && !isSharedUser);
  148. }
  149. /**
  150. * whether to display page management
  151. * ex.) duplicate, rename
  152. */
  153. get isAbleToShowPageManagement() {
  154. const { isPageExist, isTrashPage } = this.state;
  155. const { isSharedUser } = this.appContainer;
  156. return (isPageExist && !isTrashPage && !isSharedUser);
  157. }
  158. /**
  159. * whether to display pageEditorModeManager
  160. * ex.) view, edit, hackmd
  161. */
  162. get isAbleToShowPageEditorModeManager() {
  163. const { isNotCreatable, isTrashPage } = this.state;
  164. const { isSharedUser } = this.appContainer;
  165. return (!isNotCreatable && !isTrashPage && !isSharedUser);
  166. }
  167. /**
  168. * whether to display pageAuthors
  169. * ex.) creator, lastUpdateUser
  170. */
  171. get isAbleToShowPageAuthors() {
  172. const { isPageExist, isUserPage } = this.state;
  173. return (isPageExist && !isUserPage);
  174. }
  175. /**
  176. * whether to like button
  177. * not displayed on user page
  178. */
  179. get isAbleToShowLikeButton() {
  180. const { isUserPage } = this.state;
  181. const { isSharedUser } = this.appContainer;
  182. return (!isUserPage && !isSharedUser);
  183. }
  184. /**
  185. * whether to Empty Trash Page
  186. * not displayed when guest user and not on trash page
  187. */
  188. get isAbleToShowEmptyTrashButton() {
  189. const { currentUser } = this.appContainer;
  190. const { path, hasChildren } = this.state;
  191. return (currentUser != null && currentUser.admin && path === '/trash' && hasChildren);
  192. }
  193. /**
  194. * whether to display trash management buttons
  195. * ex.) undo, delete completly
  196. * not displayed when guest user
  197. */
  198. get isAbleToShowTrashPageManagementButtons() {
  199. const { currentUser } = this.appContainer;
  200. const { isDeleted } = this.state;
  201. return (isDeleted && currentUser != null);
  202. }
  203. /**
  204. * initialize state for markdown data
  205. */
  206. initStateMarkdown() {
  207. let pageContent = '';
  208. const rawText = document.getElementById('raw-text-original');
  209. if (rawText) {
  210. pageContent = rawText.innerHTML;
  211. }
  212. const markdown = entities.decodeHTML(pageContent);
  213. this.state.markdown = markdown;
  214. }
  215. async retrieveSeenUsers() {
  216. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: this.state.seenUserIds });
  217. this.setState({ seenUsers: users });
  218. this.checkAndUpdateImageUrlCached(users);
  219. }
  220. async retrieveLikeInfo() {
  221. const res = await this.appContainer.apiv3Get('/page/like-info', { _id: this.state.pageId });
  222. const { sumOfLikers, isLiked } = res.data;
  223. this.setState({
  224. sumOfLikers,
  225. isLiked,
  226. });
  227. }
  228. async toggleLike() {
  229. const bool = !this.state.isLiked;
  230. await this.appContainer.apiv3Put('/page/likes', { pageId: this.state.pageId, bool });
  231. this.setState({ isLiked: bool });
  232. return this.retrieveLikeInfo();
  233. }
  234. async retrieveBookmarkInfo() {
  235. const response = await this.appContainer.apiv3Get('/bookmarks/info', { pageId: this.state.pageId });
  236. this.setState({
  237. sumOfBookmarks: response.data.sumOfBookmarks,
  238. isBookmarked: response.data.isBookmarked,
  239. });
  240. }
  241. async toggleBookmark() {
  242. const bool = !this.state.isBookmarked;
  243. await this.appContainer.apiv3Put('/bookmarks', { pageId: this.state.pageId, bool });
  244. return this.retrieveBookmarkInfo();
  245. }
  246. async checkAndUpdateImageUrlCached(users) {
  247. const noImageCacheUsers = users.filter((user) => { return user.imageUrlCached == null });
  248. if (noImageCacheUsers.length === 0) {
  249. return;
  250. }
  251. const noImageCacheUserIds = noImageCacheUsers.map((user) => { return user.id });
  252. try {
  253. await this.appContainer.apiv3Put('/users/update.imageUrlCache', { userIds: noImageCacheUserIds });
  254. }
  255. catch (err) {
  256. // Error alert doesn't apear, because user don't need to notice this error.
  257. logger.error(err);
  258. }
  259. }
  260. get navigationContainer() {
  261. return this.appContainer.getContainer('NavigationContainer');
  262. }
  263. setLatestRemotePageData(s2cMessagePageUpdated) {
  264. const newState = {
  265. remoteRevisionId: s2cMessagePageUpdated.revisionId,
  266. revisionIdHackmdSynced: s2cMessagePageUpdated.revisionIdHackmdSynced,
  267. lastUpdateUsername: s2cMessagePageUpdated.lastUpdateUsername,
  268. };
  269. if (s2cMessagePageUpdated.hasDraftOnHackmd != null) {
  270. newState.hasDraftOnHackmd = s2cMessagePageUpdated.hasDraftOnHackmd;
  271. }
  272. this.setState(newState);
  273. }
  274. setTocHtml(tocHtml) {
  275. if (this.state.tocHtml !== tocHtml) {
  276. this.setState({ tocHtml });
  277. }
  278. }
  279. /**
  280. * save success handler
  281. * @param {object} page Page instance
  282. * @param {Array[Tag]} tags Array of Tag
  283. * @param {object} revision Revision instance
  284. */
  285. updateStateAfterSave(page, tags, revision) {
  286. const { editorMode } = this.navigationContainer.state;
  287. // update state of PageContainer
  288. const newState = {
  289. pageId: page._id,
  290. revisionId: revision._id,
  291. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  292. remoteRevisionId: revision._id,
  293. revisionIdHackmdSynced: page.revisionHackmdSynced,
  294. hasDraftOnHackmd: page.hasDraftOnHackmd,
  295. markdown: revision.body,
  296. createdAt: page.createdAt,
  297. updatedAt: page.updatedAt,
  298. };
  299. if (tags != null) {
  300. newState.tags = tags;
  301. }
  302. this.setState(newState);
  303. // PageEditor component
  304. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  305. if (pageEditor != null) {
  306. if (editorMode !== 'edit') {
  307. pageEditor.updateEditorValue(newState.markdown);
  308. }
  309. }
  310. // PageEditorByHackmd component
  311. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  312. if (pageEditorByHackmd != null) {
  313. // reset
  314. if (editorMode !== 'hackmd') {
  315. pageEditorByHackmd.reset();
  316. }
  317. }
  318. // hidden input
  319. $('input[name="revision_id"]').val(newState.revisionId);
  320. }
  321. /**
  322. * Save page
  323. * @param {string} markdown
  324. * @param {object} optionsToSave
  325. * @return {object} { page: Page, tags: Tag[] }
  326. */
  327. async save(markdown, optionsToSave = {}) {
  328. const { editorMode } = this.navigationContainer.state;
  329. const { pageId, path } = this.state;
  330. let { revisionId } = this.state;
  331. const options = Object.assign({}, optionsToSave);
  332. if (editorMode === 'hackmd') {
  333. // set option to sync
  334. options.isSyncRevisionToHackmd = true;
  335. revisionId = this.state.revisionIdHackmdSynced;
  336. }
  337. let res;
  338. if (pageId == null) {
  339. res = await this.createPage(path, markdown, options);
  340. }
  341. else {
  342. res = await this.updatePage(pageId, revisionId, markdown, options);
  343. }
  344. this.updateStateAfterSave(res.page, res.tags, res.revision);
  345. return res;
  346. }
  347. async saveAndReload(optionsToSave) {
  348. if (optionsToSave == null) {
  349. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  350. throw new Error(msg);
  351. }
  352. const { editorMode } = this.navigationContainer.state;
  353. if (editorMode == null) {
  354. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  355. return;
  356. }
  357. const { pageId, path } = this.state;
  358. let { revisionId } = this.state;
  359. const options = Object.assign({}, optionsToSave);
  360. let markdown;
  361. if (editorMode === 'hackmd') {
  362. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  363. markdown = await pageEditorByHackmd.getMarkdown();
  364. // set option to sync
  365. options.isSyncRevisionToHackmd = true;
  366. revisionId = this.state.revisionIdHackmdSynced;
  367. }
  368. else {
  369. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  370. markdown = pageEditor.getMarkdown();
  371. }
  372. let res;
  373. if (pageId == null) {
  374. res = await this.createPage(path, markdown, options);
  375. }
  376. else {
  377. res = await this.updatePage(pageId, revisionId, markdown, options);
  378. }
  379. const editorContainer = this.appContainer.getContainer('EditorContainer');
  380. editorContainer.clearDraft(path);
  381. window.location.href = path;
  382. return res;
  383. }
  384. async createPage(pagePath, markdown, tmpParams) {
  385. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  386. // clone
  387. const params = Object.assign(tmpParams, {
  388. path: pagePath,
  389. body: markdown,
  390. });
  391. const res = await this.appContainer.apiv3Post('/pages/', params);
  392. const { page, tags, revision } = res.data;
  393. return { page, tags, revision };
  394. }
  395. async updatePage(pageId, revisionId, markdown, tmpParams) {
  396. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  397. // clone
  398. const params = Object.assign(tmpParams, {
  399. page_id: pageId,
  400. revision_id: revisionId,
  401. body: markdown,
  402. });
  403. const res = await this.appContainer.apiPost('/pages.update', params);
  404. if (!res.ok) {
  405. throw new Error(res.error);
  406. }
  407. return res;
  408. }
  409. deletePage(isRecursively, isCompletely) {
  410. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  411. // control flag
  412. const completely = isCompletely ? true : null;
  413. const recursively = isRecursively ? true : null;
  414. return this.appContainer.apiPost('/pages.remove', {
  415. recursively,
  416. completely,
  417. page_id: this.state.pageId,
  418. revision_id: this.state.revisionId,
  419. });
  420. }
  421. revertRemove(isRecursively) {
  422. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  423. // control flag
  424. const recursively = isRecursively ? true : null;
  425. return this.appContainer.apiPost('/pages.revertRemove', {
  426. recursively,
  427. page_id: this.state.pageId,
  428. });
  429. }
  430. rename(newPagePath, isRecursively, isRenameRedirect, isRemainMetadata) {
  431. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  432. const { pageId, revisionId, path } = this.state;
  433. return this.appContainer.apiv3Put('/pages/rename', {
  434. revisionId,
  435. pageId,
  436. isRecursively,
  437. isRenameRedirect,
  438. isRemainMetadata,
  439. newPagePath,
  440. path,
  441. });
  442. }
  443. showSuccessToastr() {
  444. toastr.success(undefined, 'Saved successfully', {
  445. closeButton: true,
  446. progressBar: true,
  447. newestOnTop: false,
  448. showDuration: '100',
  449. hideDuration: '100',
  450. timeOut: '1200',
  451. extendedTimeOut: '150',
  452. });
  453. }
  454. showErrorToastr(error) {
  455. toastr.error(error.message, 'Error occured', {
  456. closeButton: true,
  457. progressBar: true,
  458. newestOnTop: false,
  459. showDuration: '100',
  460. hideDuration: '100',
  461. timeOut: '3000',
  462. });
  463. }
  464. // request to server so the client to join a room for each page
  465. emitJoinPageRoomRequest() {
  466. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  467. const socket = socketIoContainer.getSocket();
  468. socket.emit('join:page', { socketId: socket.id, pageId: this.state.pageId });
  469. }
  470. addWebSocketEventHandlers() {
  471. // eslint-disable-next-line @typescript-eslint/no-this-alias
  472. const pageContainer = this;
  473. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  474. const socket = socketIoContainer.getSocket();
  475. socket.on('page:create', (data) => {
  476. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  477. // update remote page data
  478. const { s2cMessagePageUpdated } = data;
  479. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  480. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  481. }
  482. });
  483. socket.on('page:update', (data) => {
  484. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  485. // update remote page data
  486. const { s2cMessagePageUpdated } = data;
  487. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  488. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  489. }
  490. });
  491. socket.on('page:delete', (data) => {
  492. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  493. // update remote page data
  494. const { s2cMessagePageUpdated } = data;
  495. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  496. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  497. }
  498. });
  499. socket.on('page:editingWithHackmd', (data) => {
  500. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  501. // update isHackmdDraftUpdatingInRealtime
  502. const { s2cMessagePageUpdated } = data;
  503. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  504. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  505. }
  506. });
  507. }
  508. /* TODO GW-325 */
  509. retrieveMyBookmarkList() {
  510. }
  511. }