PageContainer.js 18 KB

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