PageContainer.js 19 KB

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