PageContainer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 { toastError } from '../util/apiNotification';
  6. const logger = loggerFactory('growi:services:PageContainer');
  7. const scrollThresForSticky = 0;
  8. const scrollThresForCompact = 30;
  9. const scrollThresForThrottling = 100;
  10. /**
  11. * Service container related to Page
  12. * @extends {Container} unstated Container
  13. */
  14. export default class PageContainer extends Container {
  15. constructor(appContainer) {
  16. super();
  17. this.appContainer = appContainer;
  18. this.appContainer.registerContainer(this);
  19. this.state = {};
  20. const mainContent = document.querySelector('#content-main');
  21. if (mainContent == null) {
  22. logger.debug('#content-main element is not exists');
  23. return;
  24. }
  25. const revisionId = mainContent.getAttribute('data-page-revision-id');
  26. const path = decodeURI(mainContent.getAttribute('data-path'));
  27. this.state = {
  28. // local page data
  29. markdown: null, // will be initialized after initStateMarkdown()
  30. pageId: mainContent.getAttribute('data-page-id'),
  31. revisionId,
  32. revisionCreatedAt: +mainContent.getAttribute('data-page-revision-created'),
  33. revisionAuthor: JSON.parse(mainContent.getAttribute('data-page-revision-author')),
  34. path,
  35. tocHtml: '',
  36. isLiked: JSON.parse(mainContent.getAttribute('data-page-is-liked')),
  37. seenUsers: [],
  38. likerUsers: [],
  39. sumOfSeenUsers: 0,
  40. sumOfLikers: 0,
  41. createdAt: mainContent.getAttribute('data-page-created-at'),
  42. creator: JSON.parse(mainContent.getAttribute('data-page-creator')),
  43. updatedAt: mainContent.getAttribute('data-page-updated-at'),
  44. isDeleted: JSON.parse(mainContent.getAttribute('data-page-is-deleted')),
  45. isDeletable: JSON.parse(mainContent.getAttribute('data-page-is-deletable')),
  46. isAbleToDeleteCompletely: JSON.parse(mainContent.getAttribute('data-page-is-able-to-delete-completely')),
  47. tags: [],
  48. hasChildren: JSON.parse(mainContent.getAttribute('data-page-has-children')),
  49. templateTagData: mainContent.getAttribute('data-template-tags') || null,
  50. // latest(on remote) information
  51. remoteRevisionId: revisionId,
  52. revisionIdHackmdSynced: mainContent.getAttribute('data-page-revision-id-hackmd-synced') || null,
  53. lastUpdateUsername: undefined,
  54. pageIdOnHackmd: mainContent.getAttribute('data-page-id-on-hackmd') || null,
  55. hasDraftOnHackmd: !!mainContent.getAttribute('data-page-has-draft-on-hackmd'),
  56. isHackmdDraftUpdatingInRealtime: false,
  57. isHeaderSticky: false,
  58. isSubnavCompact: false,
  59. };
  60. this.initStateMarkdown();
  61. this.initStateOthers();
  62. this.setTocHtml = this.setTocHtml.bind(this);
  63. this.save = this.save.bind(this);
  64. this.checkAndUpdateImageUrlCached = this.checkAndUpdateImageUrlCached.bind(this);
  65. this.addWebSocketEventHandlers = this.addWebSocketEventHandlers.bind(this);
  66. this.addWebSocketEventHandlers();
  67. window.addEventListener('scroll', () => {
  68. const currentYOffset = window.pageYOffset;
  69. // original throttling
  70. if (this.state.isSubnavCompact && scrollThresForThrottling < currentYOffset) {
  71. return;
  72. }
  73. this.setState({
  74. isHeaderSticky: scrollThresForSticky < currentYOffset,
  75. isSubnavCompact: scrollThresForCompact < currentYOffset,
  76. });
  77. });
  78. const unlinkPageButton = document.getElementById('unlink-page-button');
  79. if (unlinkPageButton != null) {
  80. unlinkPageButton.addEventListener('click', async() => {
  81. try {
  82. const res = await this.appContainer.apiPost('/pages.unlink', { path });
  83. window.location.href = encodeURI(`${res.path}?unlinked=true`);
  84. }
  85. catch (err) {
  86. toastError(err);
  87. }
  88. });
  89. }
  90. }
  91. /**
  92. * Workaround for the mangling in production build to break constructor.name
  93. */
  94. static getClassName() {
  95. return 'PageContainer';
  96. }
  97. /**
  98. * initialize state for markdown data
  99. */
  100. initStateMarkdown() {
  101. let pageContent = '';
  102. const rawText = document.getElementById('raw-text-original');
  103. if (rawText) {
  104. pageContent = rawText.innerHTML;
  105. }
  106. const markdown = entities.decodeHTML(pageContent);
  107. this.state.markdown = markdown;
  108. }
  109. async initStateOthers() {
  110. const seenUserListElem = document.getElementById('seen-user-list');
  111. if (seenUserListElem != null) {
  112. const { userIdsStr, sumOfSeenUsers } = seenUserListElem.dataset;
  113. this.setState({ sumOfSeenUsers });
  114. if (userIdsStr === '') {
  115. return;
  116. }
  117. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: userIdsStr });
  118. this.setState({ seenUsers: users });
  119. this.checkAndUpdateImageUrlCached(users);
  120. }
  121. const likerListElem = document.getElementById('liker-list');
  122. if (likerListElem != null) {
  123. const { userIdsStr, sumOfLikers } = likerListElem.dataset;
  124. this.setState({ sumOfLikers });
  125. if (userIdsStr === '') {
  126. return;
  127. }
  128. const { users } = await this.appContainer.apiGet('/users.list', { user_ids: userIdsStr });
  129. this.setState({ likerUsers: users });
  130. this.checkAndUpdateImageUrlCached(users);
  131. }
  132. }
  133. async checkAndUpdateImageUrlCached(users) {
  134. const noImageCacheUsers = users.filter((user) => { return user.imageUrlCached == null });
  135. if (noImageCacheUsers.length === 0) {
  136. return;
  137. }
  138. const noImageCacheUserIds = noImageCacheUsers.map((user) => { return user.id });
  139. try {
  140. await this.appContainer.apiv3Put('/users/update.imageUrlCache', { userIds: noImageCacheUserIds });
  141. }
  142. catch (err) {
  143. // Error alert doesn't apear, because user don't need to notice this error.
  144. logger.error(err);
  145. }
  146. }
  147. get navigationContainer() {
  148. return this.appContainer.getContainer('NavigationContainer');
  149. }
  150. setLatestRemotePageData(page, user) {
  151. this.setState({
  152. remoteRevisionId: page.revision._id,
  153. revisionIdHackmdSynced: page.revisionHackmdSynced,
  154. lastUpdateUsername: user.name,
  155. });
  156. }
  157. setTocHtml(tocHtml) {
  158. if (this.state.tocHtml !== tocHtml) {
  159. this.setState({ tocHtml });
  160. }
  161. }
  162. /**
  163. * save success handler
  164. * @param {object} page Page instance
  165. * @param {Array[Tag]} tags Array of Tag
  166. */
  167. updateStateAfterSave(page, tags) {
  168. const { editorMode } = this.navigationContainer.state;
  169. // update state of PageContainer
  170. const newState = {
  171. pageId: page._id,
  172. revisionId: page.revision._id,
  173. revisionCreatedAt: new Date(page.revision.createdAt).getTime() / 1000,
  174. remoteRevisionId: page.revision._id,
  175. revisionIdHackmdSynced: page.revisionHackmdSynced,
  176. hasDraftOnHackmd: page.hasDraftOnHackmd,
  177. markdown: page.revision.body,
  178. };
  179. if (tags != null) {
  180. newState.tags = tags;
  181. }
  182. this.setState(newState);
  183. // PageEditor component
  184. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  185. if (pageEditor != null) {
  186. if (editorMode !== 'builtin') {
  187. pageEditor.updateEditorValue(newState.markdown);
  188. }
  189. }
  190. // PageEditorByHackmd component
  191. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  192. if (pageEditorByHackmd != null) {
  193. // reset
  194. if (editorMode !== 'hackmd') {
  195. pageEditorByHackmd.reset();
  196. }
  197. }
  198. // hidden input
  199. $('input[name="revision_id"]').val(newState.revisionId);
  200. }
  201. /**
  202. * Save page
  203. * @param {string} markdown
  204. * @param {object} optionsToSave
  205. * @return {object} { page: Page, tags: Tag[] }
  206. */
  207. async save(markdown, optionsToSave = {}) {
  208. const { editorMode } = this.navigationContainer.state;
  209. const { pageId, path } = this.state;
  210. let { revisionId } = this.state;
  211. const options = Object.assign({}, optionsToSave);
  212. if (editorMode === 'hackmd') {
  213. // set option to sync
  214. options.isSyncRevisionToHackmd = true;
  215. revisionId = this.state.revisionIdHackmdSynced;
  216. }
  217. let res;
  218. if (pageId == null) {
  219. res = await this.createPage(path, markdown, options);
  220. }
  221. else {
  222. res = await this.updatePage(pageId, revisionId, markdown, options);
  223. }
  224. this.updateStateAfterSave(res.page, res.tags);
  225. return res;
  226. }
  227. async saveAndReload(optionsToSave) {
  228. if (optionsToSave == null) {
  229. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  230. throw new Error(msg);
  231. }
  232. const { editorMode } = this.navigationContainer.state;
  233. if (editorMode == null) {
  234. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  235. return;
  236. }
  237. const { pageId, path } = this.state;
  238. let { revisionId } = this.state;
  239. const options = Object.assign({}, optionsToSave);
  240. let markdown;
  241. if (editorMode === 'hackmd') {
  242. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  243. markdown = await pageEditorByHackmd.getMarkdown();
  244. // set option to sync
  245. options.isSyncRevisionToHackmd = true;
  246. revisionId = this.state.revisionIdHackmdSynced;
  247. }
  248. else {
  249. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  250. markdown = pageEditor.getMarkdown();
  251. }
  252. let res;
  253. if (pageId == null) {
  254. res = await this.createPage(path, markdown, options);
  255. }
  256. else {
  257. res = await this.updatePage(pageId, revisionId, markdown, options);
  258. }
  259. const editorContainer = this.appContainer.getContainer('EditorContainer');
  260. editorContainer.clearDraft(path);
  261. window.location.href = path;
  262. return res;
  263. }
  264. async createPage(pagePath, markdown, tmpParams) {
  265. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  266. // clone
  267. const params = Object.assign(tmpParams, {
  268. socketClientId: websocketContainer.getSocketClientId(),
  269. path: pagePath,
  270. body: markdown,
  271. });
  272. const res = await this.appContainer.apiPost('/pages.create', params);
  273. if (!res.ok) {
  274. throw new Error(res.error);
  275. }
  276. return { page: res.page, tags: res.tags };
  277. }
  278. async updatePage(pageId, revisionId, markdown, tmpParams) {
  279. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  280. // clone
  281. const params = Object.assign(tmpParams, {
  282. socketClientId: websocketContainer.getSocketClientId(),
  283. page_id: pageId,
  284. revision_id: revisionId,
  285. body: markdown,
  286. });
  287. const res = await this.appContainer.apiPost('/pages.update', params);
  288. if (!res.ok) {
  289. throw new Error(res.error);
  290. }
  291. return { page: res.page, tags: res.tags };
  292. }
  293. deletePage(isRecursively, isCompletely) {
  294. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  295. // control flag
  296. const completely = isCompletely ? true : null;
  297. const recursively = isRecursively ? true : null;
  298. return this.appContainer.apiPost('/pages.remove', {
  299. recursively,
  300. completely,
  301. page_id: this.state.pageId,
  302. revision_id: this.state.revisionId,
  303. socketClientId: websocketContainer.getSocketClientId(),
  304. });
  305. }
  306. revertRemove(isRecursively) {
  307. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  308. // control flag
  309. const recursively = isRecursively ? true : null;
  310. return this.appContainer.apiPost('/pages.revertRemove', {
  311. recursively,
  312. page_id: this.state.pageId,
  313. socketClientId: websocketContainer.getSocketClientId(),
  314. });
  315. }
  316. rename(pageNameInput, isRenameRecursively, isRenameRedirect, isRenameMetadata) {
  317. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  318. const isRecursively = isRenameRecursively ? true : null;
  319. const isRedirect = isRenameRedirect ? true : null;
  320. const isRemain = isRenameMetadata ? true : null;
  321. return this.appContainer.apiPost('/pages.rename', {
  322. recursively: isRecursively,
  323. page_id: this.state.pageId,
  324. revision_id: this.state.revisionId,
  325. new_path: pageNameInput,
  326. create_redirect: isRedirect,
  327. remain_metadata: isRemain,
  328. socketClientId: websocketContainer.getSocketClientId(),
  329. });
  330. }
  331. showSuccessToastr() {
  332. toastr.success(undefined, 'Saved successfully', {
  333. closeButton: true,
  334. progressBar: true,
  335. newestOnTop: false,
  336. showDuration: '100',
  337. hideDuration: '100',
  338. timeOut: '1200',
  339. extendedTimeOut: '150',
  340. });
  341. }
  342. showErrorToastr(error) {
  343. toastr.error(error.message, 'Error occured', {
  344. closeButton: true,
  345. progressBar: true,
  346. newestOnTop: false,
  347. showDuration: '100',
  348. hideDuration: '100',
  349. timeOut: '3000',
  350. });
  351. }
  352. addWebSocketEventHandlers() {
  353. const pageContainer = this;
  354. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  355. const socket = websocketContainer.getWebSocket();
  356. socket.on('page:create', (data) => {
  357. // skip if triggered myself
  358. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  359. return;
  360. }
  361. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  362. // update PageStatusAlert
  363. if (data.page.path === pageContainer.state.path) {
  364. this.setLatestRemotePageData(data.page, data.user);
  365. }
  366. });
  367. socket.on('page:update', (data) => {
  368. // skip if triggered myself
  369. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  370. return;
  371. }
  372. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  373. if (data.page.path === pageContainer.state.path) {
  374. // update PageStatusAlert
  375. pageContainer.setLatestRemotePageData(data.page, data.user);
  376. // update remote data
  377. const page = data.page;
  378. pageContainer.setState({
  379. remoteRevisionId: page.revision._id,
  380. revisionIdHackmdSynced: page.revisionHackmdSynced,
  381. hasDraftOnHackmd: page.hasDraftOnHackmd,
  382. });
  383. }
  384. });
  385. socket.on('page:delete', (data) => {
  386. // skip if triggered myself
  387. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  388. return;
  389. }
  390. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  391. // update PageStatusAlert
  392. if (data.page.path === pageContainer.state.path) {
  393. pageContainer.setLatestRemotePageData(data.page, data.user);
  394. }
  395. });
  396. socket.on('page:editingWithHackmd', (data) => {
  397. // skip if triggered myself
  398. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  399. return;
  400. }
  401. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  402. if (data.page.path === pageContainer.state.path) {
  403. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  404. }
  405. });
  406. }
  407. }