PageContainer.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. isTrashPage: isTrashPage(path),
  51. isForbidden: JSON.parse(mainContent.getAttribute('data-page-is-forbidden')),
  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 { isPageForbidden, isNotCreatable, isTrashPage } = this.state;
  124. const { isGuestUser } = this.appContainer;
  125. return (!isGuestUser && !isPageForbidden && !isNotCreatable && !isTrashPage);
  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. * initialize state for markdown data
  138. */
  139. initStateMarkdown() {
  140. let pageContent = '';
  141. const rawText = document.getElementById('raw-text-original');
  142. if (rawText) {
  143. pageContent = rawText.innerHTML;
  144. }
  145. const markdown = entities.decodeHTML(pageContent);
  146. this.state.markdown = markdown;
  147. }
  148. async retrieveSeenUsers() {
  149. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: this.state.seenUserIds });
  150. this.setState({ seenUsers: users });
  151. this.checkAndUpdateImageUrlCached(users);
  152. }
  153. async retrieveLikeInfo() {
  154. const res = await this.appContainer.apiv3Get('/page/like-info', { _id: this.state.pageId });
  155. const { sumOfLikers, isLiked } = res.data;
  156. this.setState({
  157. sumOfLikers,
  158. isLiked,
  159. });
  160. }
  161. async toggleLike() {
  162. const bool = !this.state.isLiked;
  163. await this.appContainer.apiv3Put('/page/likes', { pageId: this.state.pageId, bool });
  164. this.setState({ isLiked: bool });
  165. return this.retrieveLikeInfo();
  166. }
  167. async retrieveBookmarkInfo() {
  168. const response = await this.appContainer.apiv3Get('/bookmarks/info', { pageId: this.state.pageId });
  169. this.setState({
  170. sumOfBookmarks: response.data.sumOfBookmarks,
  171. isBookmarked: response.data.isBookmarked,
  172. });
  173. }
  174. async toggleBookmark() {
  175. const bool = !this.state.isBookmarked;
  176. await this.appContainer.apiv3Put('/bookmarks', { pageId: this.state.pageId, bool });
  177. return this.retrieveBookmarkInfo();
  178. }
  179. async checkAndUpdateImageUrlCached(users) {
  180. const noImageCacheUsers = users.filter((user) => { return user.imageUrlCached == null });
  181. if (noImageCacheUsers.length === 0) {
  182. return;
  183. }
  184. const noImageCacheUserIds = noImageCacheUsers.map((user) => { return user.id });
  185. try {
  186. await this.appContainer.apiv3Put('/users/update.imageUrlCache', { userIds: noImageCacheUserIds });
  187. }
  188. catch (err) {
  189. // Error alert doesn't apear, because user don't need to notice this error.
  190. logger.error(err);
  191. }
  192. }
  193. get navigationContainer() {
  194. return this.appContainer.getContainer('NavigationContainer');
  195. }
  196. setLatestRemotePageData(s2cMessagePageUpdated) {
  197. this.setState({
  198. remoteRevisionId: s2cMessagePageUpdated.revisionId,
  199. revisionIdHackmdSynced: s2cMessagePageUpdated.revisionIdHackmdSynced,
  200. lastUpdateUsername: s2cMessagePageUpdated.lastUpdateUsername,
  201. hasDraftOnHackmd: s2cMessagePageUpdated.hasDraftOnHackmd,
  202. });
  203. }
  204. setTocHtml(tocHtml) {
  205. if (this.state.tocHtml !== tocHtml) {
  206. this.setState({ tocHtml });
  207. }
  208. }
  209. /**
  210. * save success handler
  211. * @param {object} page Page instance
  212. * @param {Array[Tag]} tags Array of Tag
  213. */
  214. updateStateAfterSave(page, tags) {
  215. const { editorMode } = this.navigationContainer.state;
  216. // update state of PageContainer
  217. const newState = {
  218. pageId: page._id,
  219. revisionId: page.revision._id,
  220. revisionCreatedAt: new Date(page.revision.createdAt).getTime() / 1000,
  221. remoteRevisionId: page.revision._id,
  222. revisionIdHackmdSynced: page.revisionHackmdSynced,
  223. hasDraftOnHackmd: page.hasDraftOnHackmd,
  224. markdown: page.revision.body,
  225. createdAt: page.createdAt,
  226. updatedAt: page.updatedAt,
  227. };
  228. if (tags != null) {
  229. newState.tags = tags;
  230. }
  231. this.setState(newState);
  232. // PageEditor component
  233. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  234. if (pageEditor != null) {
  235. if (editorMode !== 'edit') {
  236. pageEditor.updateEditorValue(newState.markdown);
  237. }
  238. }
  239. // PageEditorByHackmd component
  240. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  241. if (pageEditorByHackmd != null) {
  242. // reset
  243. if (editorMode !== 'hackmd') {
  244. pageEditorByHackmd.reset();
  245. }
  246. }
  247. // hidden input
  248. $('input[name="revision_id"]').val(newState.revisionId);
  249. }
  250. /**
  251. * Save page
  252. * @param {string} markdown
  253. * @param {object} optionsToSave
  254. * @return {object} { page: Page, tags: Tag[] }
  255. */
  256. async save(markdown, optionsToSave = {}) {
  257. const { editorMode } = this.navigationContainer.state;
  258. const { pageId, path } = this.state;
  259. let { revisionId } = this.state;
  260. const options = Object.assign({}, optionsToSave);
  261. if (editorMode === 'hackmd') {
  262. // set option to sync
  263. options.isSyncRevisionToHackmd = true;
  264. revisionId = this.state.revisionIdHackmdSynced;
  265. }
  266. let res;
  267. if (pageId == null) {
  268. res = await this.createPage(path, markdown, options);
  269. }
  270. else {
  271. res = await this.updatePage(pageId, revisionId, markdown, options);
  272. }
  273. this.updateStateAfterSave(res.page, res.tags);
  274. return res;
  275. }
  276. async saveAndReload(optionsToSave) {
  277. if (optionsToSave == null) {
  278. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  279. throw new Error(msg);
  280. }
  281. const { editorMode } = this.navigationContainer.state;
  282. if (editorMode == null) {
  283. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  284. return;
  285. }
  286. const { pageId, path } = this.state;
  287. let { revisionId } = this.state;
  288. const options = Object.assign({}, optionsToSave);
  289. let markdown;
  290. if (editorMode === 'hackmd') {
  291. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  292. markdown = await pageEditorByHackmd.getMarkdown();
  293. // set option to sync
  294. options.isSyncRevisionToHackmd = true;
  295. revisionId = this.state.revisionIdHackmdSynced;
  296. }
  297. else {
  298. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  299. markdown = pageEditor.getMarkdown();
  300. }
  301. let res;
  302. if (pageId == null) {
  303. res = await this.createPage(path, markdown, options);
  304. }
  305. else {
  306. res = await this.updatePage(pageId, revisionId, markdown, options);
  307. }
  308. const editorContainer = this.appContainer.getContainer('EditorContainer');
  309. editorContainer.clearDraft(path);
  310. window.location.href = path;
  311. return res;
  312. }
  313. async createPage(pagePath, markdown, tmpParams) {
  314. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  315. // clone
  316. const params = Object.assign(tmpParams, {
  317. socketClientId: socketIoContainer.getSocketClientId(),
  318. path: pagePath,
  319. body: markdown,
  320. });
  321. const res = await this.appContainer.apiPost('/pages.create', params);
  322. if (!res.ok) {
  323. throw new Error(res.error);
  324. }
  325. return { page: res.page, tags: res.tags };
  326. }
  327. async updatePage(pageId, revisionId, markdown, tmpParams) {
  328. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  329. // clone
  330. const params = Object.assign(tmpParams, {
  331. socketClientId: socketIoContainer.getSocketClientId(),
  332. page_id: pageId,
  333. revision_id: revisionId,
  334. body: markdown,
  335. });
  336. const res = await this.appContainer.apiPost('/pages.update', params);
  337. if (!res.ok) {
  338. throw new Error(res.error);
  339. }
  340. return { page: res.page, tags: res.tags };
  341. }
  342. deletePage(isRecursively, isCompletely) {
  343. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  344. // control flag
  345. const completely = isCompletely ? true : null;
  346. const recursively = isRecursively ? true : null;
  347. return this.appContainer.apiPost('/pages.remove', {
  348. recursively,
  349. completely,
  350. page_id: this.state.pageId,
  351. revision_id: this.state.revisionId,
  352. socketClientId: socketIoContainer.getSocketClientId(),
  353. });
  354. }
  355. revertRemove(isRecursively) {
  356. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  357. // control flag
  358. const recursively = isRecursively ? true : null;
  359. return this.appContainer.apiPost('/pages.revertRemove', {
  360. recursively,
  361. page_id: this.state.pageId,
  362. socketClientId: socketIoContainer.getSocketClientId(),
  363. });
  364. }
  365. rename(pageNameInput, isRenameRecursively, isRenameRedirect, isRenameMetadata) {
  366. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  367. const isRecursively = isRenameRecursively ? true : null;
  368. const isRedirect = isRenameRedirect ? true : null;
  369. const isRemain = isRenameMetadata ? true : null;
  370. return this.appContainer.apiPost('/pages.rename', {
  371. recursively: isRecursively,
  372. page_id: this.state.pageId,
  373. revision_id: this.state.revisionId,
  374. new_path: pageNameInput,
  375. create_redirect: isRedirect,
  376. remain_metadata: isRemain,
  377. socketClientId: socketIoContainer.getSocketClientId(),
  378. });
  379. }
  380. showSuccessToastr() {
  381. toastr.success(undefined, 'Saved successfully', {
  382. closeButton: true,
  383. progressBar: true,
  384. newestOnTop: false,
  385. showDuration: '100',
  386. hideDuration: '100',
  387. timeOut: '1200',
  388. extendedTimeOut: '150',
  389. });
  390. }
  391. showErrorToastr(error) {
  392. toastr.error(error.message, 'Error occured', {
  393. closeButton: true,
  394. progressBar: true,
  395. newestOnTop: false,
  396. showDuration: '100',
  397. hideDuration: '100',
  398. timeOut: '3000',
  399. });
  400. }
  401. addWebSocketEventHandlers() {
  402. const pageContainer = this;
  403. const socketIoContainer = this.appContainer.getContainer('SocketIoContainer');
  404. const socket = socketIoContainer.getSocket();
  405. socket.on('page:create', (data) => {
  406. // skip if triggered myself
  407. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  408. return;
  409. }
  410. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  411. // update remote page data
  412. const { s2cMessagePageUpdated } = data;
  413. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  414. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  415. }
  416. });
  417. socket.on('page:update', (data) => {
  418. // skip if triggered myself
  419. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  420. return;
  421. }
  422. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  423. // update remote page data
  424. const { s2cMessagePageUpdated } = data;
  425. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  426. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  427. }
  428. });
  429. socket.on('page:delete', (data) => {
  430. // skip if triggered myself
  431. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  432. return;
  433. }
  434. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  435. // update remote page data
  436. const { s2cMessagePageUpdated } = data;
  437. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  438. pageContainer.setLatestRemotePageData(s2cMessagePageUpdated);
  439. }
  440. });
  441. socket.on('page:editingWithHackmd', (data) => {
  442. // skip if triggered myself
  443. if (data.socketClientId != null && data.socketClientId === socketIoContainer.getSocketClientId()) {
  444. return;
  445. }
  446. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  447. // update isHackmdDraftUpdatingInRealtime
  448. const { s2cMessagePageUpdated } = data;
  449. if (s2cMessagePageUpdated.pageId === pageContainer.state.pageId) {
  450. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  451. }
  452. });
  453. }
  454. /* TODO GW-325 */
  455. retrieveMyBookmarkList() {
  456. }
  457. }