PageContainer.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. /**
  131. * whether to display reaction buttons
  132. * ex.) like, bookmark
  133. */
  134. get isAbleToShowPageReactionButtons() {
  135. const { isTrashPage, isPageExist } = this.state;
  136. const { isSharedUser } = this.appContainer;
  137. return (!isTrashPage && isPageExist && !isSharedUser);
  138. }
  139. /**
  140. * whether to display tag labels
  141. */
  142. get isAbleToShowTagLabel() {
  143. const { isUserPage } = this.state;
  144. const { isSharedUser } = this.appContainer;
  145. return (!isUserPage && !isSharedUser);
  146. }
  147. /**
  148. * whether to display page management
  149. * ex.) duplicate, rename
  150. */
  151. get isAbleToShowPageManagement() {
  152. const { isPageExist, isTrashPage } = this.state;
  153. const { isSharedUser } = this.appContainer;
  154. return (isPageExist && !isTrashPage && !isSharedUser);
  155. }
  156. /**
  157. * whether to display pageEditorModeManager
  158. * ex.) view, edit, hackmd
  159. */
  160. get isAbleToShowPageEditorModeManager() {
  161. const { isNotCreatable, isTrashPage } = this.state;
  162. const { isSharedUser } = this.appContainer;
  163. return (!isNotCreatable && !isTrashPage && !isSharedUser);
  164. }
  165. /**
  166. * whether to display pageAuthors
  167. * ex.) creator, lastUpdateUser
  168. */
  169. get isAbleToShowPageAuthors() {
  170. const { isPageExist, isUserPage } = this.state;
  171. return (isPageExist && !isUserPage);
  172. }
  173. /**
  174. * whether to like button
  175. * not displayed on user page
  176. */
  177. get isAbleToShowLikeButtons() {
  178. const { isUserPage } = this.state;
  179. const { isSharedUser } = this.appContainer;
  180. return (!isUserPage && !isSharedUser);
  181. }
  182. /**
  183. * whether to Empty Trash Page
  184. * not displayed when guest user and not on trash page
  185. */
  186. get isAbleToShowEmptyTrashButton() {
  187. const { currentUser } = this.appContainer;
  188. const { path, hasChildren } = this.state;
  189. return (currentUser != null && currentUser.admin && path === '/trash' && hasChildren);
  190. }
  191. /**
  192. * whether to display trash management buttons
  193. * ex.) undo, delete completly
  194. * not displayed when guest user
  195. */
  196. get isAbleToShowTrashPageManagementButtons() {
  197. const { currentUser } = this.appContainer;
  198. const { isDeleted } = this.state;
  199. return (isDeleted && currentUser != null);
  200. }
  201. /**
  202. * initialize state for markdown data
  203. */
  204. initStateMarkdown() {
  205. let pageContent = '';
  206. const rawText = document.getElementById('raw-text-original');
  207. if (rawText) {
  208. pageContent = rawText.innerHTML;
  209. }
  210. const markdown = entities.decodeHTML(pageContent);
  211. this.state.markdown = markdown;
  212. }
  213. async initialPageLoad() {
  214. {
  215. const {
  216. data: {
  217. likerIds, sumOfLikers, isLiked, seenUserIds, sumOfSeenUsers, isSeen,
  218. },
  219. } = await this.appContainer.apiv3Get('/page/info', { pageId: this.state.pageId });
  220. await this.setState({
  221. sumOfLikers,
  222. isLiked,
  223. likerIds,
  224. seenUserIds,
  225. sumOfSeenUsers,
  226. isSeen,
  227. });
  228. }
  229. await this.retrieveLikersAndSeenUsers();
  230. }
  231. async retrieveLikersAndSeenUsers() {
  232. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: [...this.state.likerIds, ...this.state.seenUserIds].join(',') });
  233. await this.setState({
  234. likers: users.filter(({ id }) => this.state.likerIds.includes(id)).slice(0, 15),
  235. seenUsers: users.filter(({ id }) => this.state.seenUserIds.includes(id)).slice(0, 15),
  236. });
  237. this.checkAndUpdateImageUrlCached(users);
  238. }
  239. async retrieveBookmarkInfo() {
  240. const response = await this.appContainer.apiv3Get('/bookmarks/info', { pageId: this.state.pageId });
  241. this.setState({
  242. sumOfBookmarks: response.data.sumOfBookmarks,
  243. isBookmarked: response.data.isBookmarked,
  244. });
  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. 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, editorMode) {
  283. // update state of PageContainer
  284. const newState = {
  285. pageId: page._id,
  286. revisionId: revision._id,
  287. revisionCreatedAt: new Date(revision.createdAt).getTime() / 1000,
  288. remoteRevisionId: revision._id,
  289. revisionIdHackmdSynced: page.revisionHackmdSynced,
  290. hasDraftOnHackmd: page.hasDraftOnHackmd,
  291. markdown: revision.body,
  292. createdAt: page.createdAt,
  293. updatedAt: page.updatedAt,
  294. };
  295. if (tags != null) {
  296. newState.tags = tags;
  297. }
  298. this.setState(newState);
  299. // PageEditor component
  300. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  301. if (pageEditor != null) {
  302. if (editorMode !== 'edit') {
  303. pageEditor.updateEditorValue(newState.markdown);
  304. }
  305. }
  306. // PageEditorByHackmd component
  307. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  308. if (pageEditorByHackmd != null) {
  309. // reset
  310. if (editorMode !== 'hackmd') {
  311. pageEditorByHackmd.reset();
  312. }
  313. }
  314. // hidden input
  315. $('input[name="revision_id"]').val(newState.revisionId);
  316. }
  317. /**
  318. * Save page
  319. * @param {string} markdown
  320. * @param {object} optionsToSave
  321. * @return {object} { page: Page, tags: Tag[] }
  322. */
  323. async save(markdown, editorMode, optionsToSave = {}) {
  324. const { pageId, path } = this.state;
  325. let { revisionId } = this.state;
  326. const options = Object.assign({}, optionsToSave);
  327. if (editorMode === 'hackmd') {
  328. // set option to sync
  329. options.isSyncRevisionToHackmd = true;
  330. revisionId = this.state.revisionIdHackmdSynced;
  331. }
  332. let res;
  333. if (pageId == null) {
  334. res = await this.createPage(path, markdown, options);
  335. }
  336. else {
  337. res = await this.updatePage(pageId, revisionId, markdown, options);
  338. }
  339. this.updateStateAfterSave(res.page, res.tags, res.revision, editorMode);
  340. return res;
  341. }
  342. async saveAndReload(optionsToSave, editorMode) {
  343. if (optionsToSave == null) {
  344. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  345. throw new Error(msg);
  346. }
  347. if (editorMode == null) {
  348. logger.warn('\'saveAndReload\' requires the \'editorMode\' param');
  349. return;
  350. }
  351. const { pageId, path } = this.state;
  352. let { revisionId } = this.state;
  353. const options = Object.assign({}, optionsToSave);
  354. let markdown;
  355. if (editorMode === 'hackmd') {
  356. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  357. markdown = await pageEditorByHackmd.getMarkdown();
  358. // set option to sync
  359. options.isSyncRevisionToHackmd = true;
  360. revisionId = this.state.revisionIdHackmdSynced;
  361. }
  362. else {
  363. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  364. markdown = pageEditor.getMarkdown();
  365. }
  366. let res;
  367. if (pageId == null) {
  368. res = await this.createPage(path, markdown, options);
  369. }
  370. else {
  371. res = await this.updatePage(pageId, revisionId, markdown, options);
  372. }
  373. const editorContainer = this.appContainer.getContainer('EditorContainer');
  374. editorContainer.clearDraft(path);
  375. window.location.href = path;
  376. return res;
  377. }
  378. async createPage(pagePath, markdown, tmpParams) {
  379. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  380. // clone
  381. const params = Object.assign(tmpParams, {
  382. path: pagePath,
  383. body: markdown,
  384. });
  385. const res = await this.appContainer.apiv3Post('/pages/', params);
  386. const { page, tags, revision } = res.data;
  387. return { page, tags, revision };
  388. }
  389. async updatePage(pageId, revisionId, markdown, tmpParams) {
  390. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  391. // clone
  392. const params = Object.assign(tmpParams, {
  393. page_id: pageId,
  394. revision_id: revisionId,
  395. body: markdown,
  396. });
  397. const res = await this.appContainer.apiPost('/pages.update', params);
  398. if (!res.ok) {
  399. throw new Error(res.error);
  400. }
  401. return res;
  402. }
  403. showSuccessToastr() {
  404. toastr.success(undefined, 'Saved successfully', {
  405. closeButton: true,
  406. progressBar: true,
  407. newestOnTop: false,
  408. showDuration: '100',
  409. hideDuration: '100',
  410. timeOut: '1200',
  411. extendedTimeOut: '150',
  412. });
  413. }
  414. showErrorToastr(error) {
  415. toastr.error(error.message, 'Error occured', {
  416. closeButton: true,
  417. progressBar: true,
  418. newestOnTop: false,
  419. showDuration: '100',
  420. hideDuration: '100',
  421. timeOut: '3000',
  422. });
  423. }
  424. // request to server so the client to join a room for each page
  425. emitJoinPageRoomRequest() {
  426. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  427. const socket = socketIoContainer.getSocket();
  428. socket.emit('join:page', { socketId: socket.id, pageId: this.state.pageId });
  429. }
  430. addWebSocketEventHandlers() {
  431. // eslint-disable-next-line @typescript-eslint/no-this-alias
  432. const pageContainer = this;
  433. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  434. const socket = socketIoContainer.getSocket();
  435. socket.on('page:create', (data) => {
  436. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  437. // update remote page data
  438. const { s2cMessagePageUpdated } = data;
  439. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  440. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  441. }
  442. });
  443. socket.on('page:update', (data) => {
  444. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  445. // update remote page data
  446. const { s2cMessagePageUpdated } = data;
  447. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  448. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  449. }
  450. });
  451. socket.on('page:delete', (data) => {
  452. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  453. // update remote page data
  454. const { s2cMessagePageUpdated } = data;
  455. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  456. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  457. }
  458. });
  459. socket.on('page:editingWithHackmd', (data) => {
  460. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  461. // update isHackmdDraftUpdatingInRealtime
  462. const { s2cMessagePageUpdated } = data;
  463. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  464. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  465. }
  466. });
  467. }
  468. /* TODO GW-325 */
  469. retrieveMyBookmarkList() {
  470. }
  471. }