PageContainer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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 checkAndUpdateImageUrlCached(users) {
  266. const noImageCacheUsers = users.filter((user) => { return user.imageUrlCached == null });
  267. if (noImageCacheUsers.length === 0) {
  268. return;
  269. }
  270. const noImageCacheUserIds = noImageCacheUsers.map((user) => { return user.id });
  271. try {
  272. await this.appContainer.apiv3Put('/users/update.imageUrlCache', { userIds: noImageCacheUserIds });
  273. }
  274. catch (err) {
  275. // Error alert doesn't apear, because user don't need to notice this error.
  276. logger.error(err);
  277. }
  278. }
  279. get navigationContainer() {
  280. return this.appContainer.getContainer('NavigationContainer');
  281. }
  282. setLatestRemotePageData(s2cMessagePageUpdated) {
  283. const newState = {
  284. remoteRevisionId: s2cMessagePageUpdated.revisionId,
  285. revisionIdHackmdSynced: s2cMessagePageUpdated.revisionIdHackmdSynced,
  286. lastUpdateUsername: s2cMessagePageUpdated.lastUpdateUsername,
  287. };
  288. if (s2cMessagePageUpdated.hasDraftOnHackmd != null) {
  289. newState.hasDraftOnHackmd = s2cMessagePageUpdated.hasDraftOnHackmd;
  290. }
  291. this.setState(newState);
  292. }
  293. setTocHtml(tocHtml) {
  294. if (this.state.tocHtml !== tocHtml) {
  295. this.setState({ tocHtml });
  296. }
  297. }
  298. /**
  299. * save success handler
  300. * @param {object} page Page instance
  301. * @param {Array[Tag]} tags Array of Tag
  302. * @param {object} revision Revision instance
  303. */
  304. updateStateAfterSave(page, tags, revision) {
  305. const { editorMode } = this.navigationContainer.state;
  306. // update state of PageContainer
  307. const newState = {
  308. pageId: page._id,
  309. revisionId: revision._id,
  310. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  311. remoteRevisionId: revision._id,
  312. revisionIdHackmdSynced: page.revisionHackmdSynced,
  313. hasDraftOnHackmd: page.hasDraftOnHackmd,
  314. markdown: revision.body,
  315. createdAt: page.createdAt,
  316. updatedAt: page.updatedAt,
  317. };
  318. if (tags != null) {
  319. newState.tags = tags;
  320. }
  321. this.setState(newState);
  322. // PageEditor component
  323. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  324. if (pageEditor != null) {
  325. if (editorMode !== 'edit') {
  326. pageEditor.updateEditorValue(newState.markdown);
  327. }
  328. }
  329. // PageEditorByHackmd component
  330. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  331. if (pageEditorByHackmd != null) {
  332. // reset
  333. if (editorMode !== 'hackmd') {
  334. pageEditorByHackmd.reset();
  335. }
  336. }
  337. // hidden input
  338. $('input[name="revision_id"]').val(newState.revisionId);
  339. }
  340. /**
  341. * Save page
  342. * @param {string} markdown
  343. * @param {object} optionsToSave
  344. * @return {object} { page: Page, tags: Tag[] }
  345. */
  346. async save(markdown, optionsToSave = {}) {
  347. const { editorMode } = this.navigationContainer.state;
  348. const { pageId, path } = this.state;
  349. let { revisionId } = this.state;
  350. const options = Object.assign({}, optionsToSave);
  351. if (editorMode === 'hackmd') {
  352. // set option to sync
  353. options.isSyncRevisionToHackmd = true;
  354. revisionId = this.state.revisionIdHackmdSynced;
  355. }
  356. let res;
  357. if (pageId == null) {
  358. res = await this.createPage(path, markdown, options);
  359. }
  360. else {
  361. res = await this.updatePage(pageId, revisionId, markdown, options);
  362. }
  363. this.updateStateAfterSave(res.page, res.tags, res.revision);
  364. return res;
  365. }
  366. async saveAndReload(optionsToSave) {
  367. if (optionsToSave == null) {
  368. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  369. throw new Error(msg);
  370. }
  371. const { editorMode } = this.navigationContainer.state;
  372. if (editorMode == null) {
  373. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  374. return;
  375. }
  376. const { pageId, path } = this.state;
  377. let { revisionId } = this.state;
  378. const options = Object.assign({}, optionsToSave);
  379. let markdown;
  380. if (editorMode === 'hackmd') {
  381. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  382. markdown = await pageEditorByHackmd.getMarkdown();
  383. // set option to sync
  384. options.isSyncRevisionToHackmd = true;
  385. revisionId = this.state.revisionIdHackmdSynced;
  386. }
  387. else {
  388. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  389. markdown = pageEditor.getMarkdown();
  390. }
  391. let res;
  392. if (pageId == null) {
  393. res = await this.createPage(path, markdown, options);
  394. }
  395. else {
  396. res = await this.updatePage(pageId, revisionId, markdown, options);
  397. }
  398. const editorContainer = this.appContainer.getContainer('EditorContainer');
  399. editorContainer.clearDraft(path);
  400. window.location.href = path;
  401. return res;
  402. }
  403. async createPage(pagePath, markdown, tmpParams) {
  404. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  405. // clone
  406. const params = Object.assign(tmpParams, {
  407. path: pagePath,
  408. body: markdown,
  409. });
  410. const res = await this.appContainer.apiv3Post('/pages/', params);
  411. const { page, tags, revision } = res.data;
  412. return { page, tags, revision };
  413. }
  414. async updatePage(pageId, revisionId, markdown, tmpParams) {
  415. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  416. // clone
  417. const params = Object.assign(tmpParams, {
  418. page_id: pageId,
  419. revision_id: revisionId,
  420. body: markdown,
  421. });
  422. const res = await this.appContainer.apiPost('/pages.update', params);
  423. if (!res.ok) {
  424. throw new Error(res.error);
  425. }
  426. return res;
  427. }
  428. revertRemove(isRecursively, pageId = this.state.pageId) {
  429. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  430. // control flag
  431. const recursively = isRecursively ? true : null;
  432. return this.appContainer.apiPost('/pages.revertRemove', {
  433. recursively,
  434. page_id: pageId,
  435. });
  436. }
  437. rename(newPagePath, isRecursively, isRenameRedirect, isRemainMetadata, pageId = this.state.pageId, revisionId = this.state.revisionId, path = this.state.path) {
  438. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  439. return this.appContainer.apiv3Put('/pages/rename', {
  440. revisionId,
  441. pageId,
  442. isRecursively,
  443. isRenameRedirect,
  444. isRemainMetadata,
  445. newPagePath,
  446. path,
  447. });
  448. }
  449. showSuccessToastr() {
  450. toastr.success(undefined, 'Saved successfully', {
  451. closeButton: true,
  452. progressBar: true,
  453. newestOnTop: false,
  454. showDuration: '100',
  455. hideDuration: '100',
  456. timeOut: '1200',
  457. extendedTimeOut: '150',
  458. });
  459. }
  460. showErrorToastr(error) {
  461. toastr.error(error.message, 'Error occured', {
  462. closeButton: true,
  463. progressBar: true,
  464. newestOnTop: false,
  465. showDuration: '100',
  466. hideDuration: '100',
  467. timeOut: '3000',
  468. });
  469. }
  470. // request to server so the client to join a room for each page
  471. emitJoinPageRoomRequest() {
  472. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  473. const socket = socketIoContainer.getSocket();
  474. socket.emit('join:page', { socketId: socket.id, pageId: this.state.pageId });
  475. }
  476. addWebSocketEventHandlers() {
  477. // eslint-disable-next-line @typescript-eslint/no-this-alias
  478. const pageContainer = this;
  479. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  480. const socket = socketIoContainer.getSocket();
  481. socket.on('page:create', (data) => {
  482. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  483. // update remote page data
  484. const { s2cMessagePageUpdated } = data;
  485. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  486. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  487. }
  488. });
  489. socket.on('page:update', (data) => {
  490. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  491. // update remote page data
  492. const { s2cMessagePageUpdated } = data;
  493. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  494. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  495. }
  496. });
  497. socket.on('page:delete', (data) => {
  498. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  499. // update remote page data
  500. const { s2cMessagePageUpdated } = data;
  501. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  502. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  503. }
  504. });
  505. socket.on('page:editingWithHackmd', (data) => {
  506. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  507. // update isHackmdDraftUpdatingInRealtime
  508. const { s2cMessagePageUpdated } = data;
  509. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  510. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  511. }
  512. });
  513. }
  514. /* TODO GW-325 */
  515. retrieveMyBookmarkList() {
  516. }
  517. }