PageContainer.js 20 KB

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