PageContainer.js 20 KB

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