PageContainer.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { Container } from 'unstated';
  2. import loggerFactory from '@alias/logger';
  3. import * as entities from 'entities';
  4. import * as toastr from 'toastr';
  5. const logger = loggerFactory('growi:services:PageContainer');
  6. const scrollThresForSticky = 0;
  7. const scrollThresForCompact = 30;
  8. const scrollThresForThrottling = 100;
  9. /**
  10. * Service container related to Page
  11. * @extends {Container} unstated Container
  12. */
  13. export default class PageContainer extends Container {
  14. constructor(appContainer) {
  15. super();
  16. this.appContainer = appContainer;
  17. this.appContainer.registerContainer(this);
  18. this.state = {};
  19. const mainContent = document.querySelector('#content-main');
  20. if (mainContent == null) {
  21. logger.debug('#content-main element is not exists');
  22. return;
  23. }
  24. const revisionId = mainContent.getAttribute('data-page-revision-id');
  25. const path = decodeURI(mainContent.getAttribute('data-path'));
  26. this.state = {
  27. // local page data
  28. markdown: null, // will be initialized after initStateMarkdown()
  29. pageId: mainContent.getAttribute('data-page-id'),
  30. revisionId,
  31. revisionCreatedAt: +mainContent.getAttribute('data-page-revision-created'),
  32. revisionAuthor: JSON.parse(mainContent.getAttribute('data-page-revision-author')),
  33. path,
  34. tocHtml: '',
  35. isLiked: JSON.parse(mainContent.getAttribute('data-page-is-liked')),
  36. seenUserIds: [],
  37. likerUserIds: [],
  38. createdAt: mainContent.getAttribute('data-page-created-at'),
  39. creator: JSON.parse(mainContent.getAttribute('data-page-creator')),
  40. updatedAt: mainContent.getAttribute('data-page-updated-at'),
  41. isDeleted: JSON.parse(mainContent.getAttribute('data-page-is-deleted')),
  42. isAbleToDeleteCompletely: JSON.parse(mainContent.getAttribute('data-page-is-able-to-delete-completely')),
  43. tags: [],
  44. hasChildren: JSON.parse(mainContent.getAttribute('data-page-has-children')),
  45. templateTagData: mainContent.getAttribute('data-template-tags') || null,
  46. // latest(on remote) information
  47. remoteRevisionId: revisionId,
  48. revisionIdHackmdSynced: mainContent.getAttribute('data-page-revision-id-hackmd-synced') || null,
  49. lastUpdateUsername: undefined,
  50. pageIdOnHackmd: mainContent.getAttribute('data-page-id-on-hackmd') || null,
  51. hasDraftOnHackmd: !!mainContent.getAttribute('data-page-has-draft-on-hackmd'),
  52. isHackmdDraftUpdatingInRealtime: false,
  53. isPageDuplicateModalShown: false,
  54. isRenameRecursively: true,
  55. isRenameRedirect: false,
  56. isRenameMetadata: 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.addWebSocketEventHandlers = this.addWebSocketEventHandlers.bind(this);
  65. this.addWebSocketEventHandlers();
  66. window.addEventListener('scroll', () => {
  67. const currentYOffset = window.pageYOffset;
  68. // original throttling
  69. if (this.state.isSubnavCompact && scrollThresForThrottling < currentYOffset) {
  70. return;
  71. }
  72. this.setState({
  73. isHeaderSticky: scrollThresForSticky < currentYOffset,
  74. isSubnavCompact: scrollThresForCompact < currentYOffset,
  75. });
  76. });
  77. this.openPageDuplicateModal = this.openPageDuplicateModal.bind(this);
  78. this.closePageDuplicateModal = this.closePageDuplicateModal.bind(this);
  79. }
  80. /**
  81. * Workaround for the mangling in production build to break constructor.name
  82. */
  83. static getClassName() {
  84. return 'PageContainer';
  85. }
  86. /**
  87. * initialize state for markdown data
  88. */
  89. initStateMarkdown() {
  90. let pageContent = '';
  91. const rawText = document.getElementById('raw-text-original');
  92. if (rawText) {
  93. pageContent = rawText.innerHTML;
  94. }
  95. const markdown = entities.decodeHTML(pageContent);
  96. this.state.markdown = markdown;
  97. }
  98. initStateOthers() {
  99. const seenUserListElem = document.getElementById('seen-user-list');
  100. if (seenUserListElem != null) {
  101. const userIdsStr = seenUserListElem.dataset.userIds;
  102. this.state.seenUserIds = userIdsStr.split(',');
  103. }
  104. const likerListElem = document.getElementById('liker-list');
  105. if (likerListElem != null) {
  106. const userIdsStr = likerListElem.dataset.userIds;
  107. this.state.likerUserIds = userIdsStr.split(',');
  108. }
  109. }
  110. setLatestRemotePageData(page, user) {
  111. this.setState({
  112. remoteRevisionId: page.revision._id,
  113. revisionIdHackmdSynced: page.revisionHackmdSynced,
  114. lastUpdateUsername: user.name,
  115. });
  116. }
  117. setTocHtml(tocHtml) {
  118. if (this.state.tocHtml !== tocHtml) {
  119. this.setState({ tocHtml });
  120. }
  121. }
  122. /**
  123. * save success handler
  124. * @param {object} page Page instance
  125. * @param {Array[Tag]} tags Array of Tag
  126. */
  127. updateStateAfterSave(page, tags) {
  128. const { editorMode } = this.appContainer.state;
  129. // update state of PageContainer
  130. const newState = {
  131. pageId: page._id,
  132. revisionId: page.revision._id,
  133. revisionCreatedAt: new Date(page.revision.createdAt).getTime() / 1000,
  134. remoteRevisionId: page.revision._id,
  135. revisionIdHackmdSynced: page.revisionHackmdSynced,
  136. hasDraftOnHackmd: page.hasDraftOnHackmd,
  137. markdown: page.revision.body,
  138. };
  139. if (tags != null) {
  140. newState.tags = tags;
  141. }
  142. this.setState(newState);
  143. // PageEditor component
  144. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  145. if (pageEditor != null) {
  146. if (editorMode !== 'builtin') {
  147. pageEditor.updateEditorValue(newState.markdown);
  148. }
  149. }
  150. // PageEditorByHackmd component
  151. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  152. if (pageEditorByHackmd != null) {
  153. // reset
  154. if (editorMode !== 'hackmd') {
  155. pageEditorByHackmd.reset();
  156. }
  157. }
  158. // hidden input
  159. $('input[name="revision_id"]').val(newState.revisionId);
  160. }
  161. /**
  162. * Save page
  163. * @param {string} markdown
  164. * @param {object} optionsToSave
  165. * @return {object} { page: Page, tags: Tag[] }
  166. */
  167. async save(markdown, optionsToSave = {}) {
  168. const { editorMode } = this.appContainer.state;
  169. const { pageId, path } = this.state;
  170. let { revisionId } = this.state;
  171. const options = Object.assign({}, optionsToSave);
  172. if (editorMode === 'hackmd') {
  173. // set option to sync
  174. options.isSyncRevisionToHackmd = true;
  175. revisionId = this.state.revisionIdHackmdSynced;
  176. }
  177. let res;
  178. if (pageId == null) {
  179. res = await this.createPage(path, markdown, options);
  180. }
  181. else {
  182. res = await this.updatePage(pageId, revisionId, markdown, options);
  183. }
  184. this.updateStateAfterSave(res.page, res.tags);
  185. return res;
  186. }
  187. async saveAndReload(optionsToSave) {
  188. if (optionsToSave == null) {
  189. const msg = '\'saveAndReload\' requires the \'optionsToSave\' param';
  190. throw new Error(msg);
  191. }
  192. const { editorMode } = this.appContainer.state;
  193. if (editorMode == null) {
  194. logger.warn('\'saveAndReload\' requires the \'errorMode\' param');
  195. return;
  196. }
  197. const { pageId, path } = this.state;
  198. let { revisionId } = this.state;
  199. const options = Object.assign({}, optionsToSave);
  200. let markdown;
  201. if (editorMode === 'hackmd') {
  202. const pageEditorByHackmd = this.appContainer.getComponentInstance('PageEditorByHackmd');
  203. markdown = await pageEditorByHackmd.getMarkdown();
  204. // set option to sync
  205. options.isSyncRevisionToHackmd = true;
  206. revisionId = this.state.revisionIdHackmdSynced;
  207. }
  208. else {
  209. const pageEditor = this.appContainer.getComponentInstance('PageEditor');
  210. markdown = pageEditor.getMarkdown();
  211. }
  212. let res;
  213. if (pageId == null) {
  214. res = await this.createPage(path, markdown, options);
  215. }
  216. else {
  217. res = await this.updatePage(pageId, revisionId, markdown, options);
  218. }
  219. const editorContainer = this.appContainer.getContainer('EditorContainer');
  220. editorContainer.clearDraft(path);
  221. window.location.href = path;
  222. return res;
  223. }
  224. async createPage(pagePath, markdown, tmpParams) {
  225. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  226. // clone
  227. const params = Object.assign(tmpParams, {
  228. socketClientId: websocketContainer.getSocketClientId(),
  229. path: pagePath,
  230. body: markdown,
  231. });
  232. const res = await this.appContainer.apiPost('/pages.create', params);
  233. if (!res.ok) {
  234. throw new Error(res.error);
  235. }
  236. return { page: res.page, tags: res.tags };
  237. }
  238. async updatePage(pageId, revisionId, markdown, tmpParams) {
  239. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  240. // clone
  241. const params = Object.assign(tmpParams, {
  242. socketClientId: websocketContainer.getSocketClientId(),
  243. page_id: pageId,
  244. revision_id: revisionId,
  245. body: markdown,
  246. });
  247. const res = await this.appContainer.apiPost('/pages.update', params);
  248. if (!res.ok) {
  249. throw new Error(res.error);
  250. }
  251. return { page: res.page, tags: res.tags };
  252. }
  253. showSuccessToastr() {
  254. toastr.success(undefined, 'Saved successfully', {
  255. closeButton: true,
  256. progressBar: true,
  257. newestOnTop: false,
  258. showDuration: '100',
  259. hideDuration: '100',
  260. timeOut: '1200',
  261. extendedTimeOut: '150',
  262. });
  263. }
  264. showErrorToastr(error) {
  265. toastr.error(error.message, 'Error occured', {
  266. closeButton: true,
  267. progressBar: true,
  268. newestOnTop: false,
  269. showDuration: '100',
  270. hideDuration: '100',
  271. timeOut: '3000',
  272. });
  273. }
  274. addWebSocketEventHandlers() {
  275. const pageContainer = this;
  276. const websocketContainer = this.appContainer.getContainer('WebsocketContainer');
  277. const socket = websocketContainer.getWebSocket();
  278. socket.on('page:create', (data) => {
  279. // skip if triggered myself
  280. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  281. return;
  282. }
  283. logger.debug({ obj: data }, `websocket on 'page:create'`); // eslint-disable-line quotes
  284. // update PageStatusAlert
  285. if (data.page.path === pageContainer.state.path) {
  286. this.setLatestRemotePageData(data.page, data.user);
  287. }
  288. });
  289. socket.on('page:update', (data) => {
  290. // skip if triggered myself
  291. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  292. return;
  293. }
  294. logger.debug({ obj: data }, `websocket on 'page:update'`); // eslint-disable-line quotes
  295. if (data.page.path === pageContainer.state.path) {
  296. // update PageStatusAlert
  297. pageContainer.setLatestRemotePageData(data.page, data.user);
  298. // update remote data
  299. const page = data.page;
  300. pageContainer.setState({
  301. remoteRevisionId: page.revision._id,
  302. revisionIdHackmdSynced: page.revisionHackmdSynced,
  303. hasDraftOnHackmd: page.hasDraftOnHackmd,
  304. });
  305. }
  306. });
  307. socket.on('page:delete', (data) => {
  308. // skip if triggered myself
  309. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  310. return;
  311. }
  312. logger.debug({ obj: data }, `websocket on 'page:delete'`); // eslint-disable-line quotes
  313. // update PageStatusAlert
  314. if (data.page.path === pageContainer.state.path) {
  315. pageContainer.setLatestRemotePageData(data.page, data.user);
  316. }
  317. });
  318. socket.on('page:editingWithHackmd', (data) => {
  319. // skip if triggered myself
  320. if (data.socketClientId != null && data.socketClientId === websocketContainer.getSocketClientId()) {
  321. return;
  322. }
  323. logger.debug({ obj: data }, `websocket on 'page:editingWithHackmd'`); // eslint-disable-line quotes
  324. if (data.page.path === pageContainer.state.path) {
  325. pageContainer.setState({ isHackmdDraftUpdatingInRealtime: true });
  326. }
  327. });
  328. }
  329. openPageDuplicateModal() {
  330. this.setState({ isPageDuplicateModalShown: true });
  331. }
  332. closePageDuplicateModal() {
  333. this.setState({ isPageDuplicateModalShown: false });
  334. }
  335. }