EditorContainer.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { Container } from 'unstated';
  2. import loggerFactory from '~/utils/logger';
  3. const logger = loggerFactory('growi:services:EditorContainer');
  4. /**
  5. * Service container related to options for Editor/Preview
  6. * @extends {Container} unstated Container
  7. */
  8. export default class EditorContainer extends Container {
  9. constructor(appContainer) {
  10. super();
  11. this.appContainer = appContainer;
  12. this.appContainer.registerContainer(this);
  13. this.state = {
  14. tags: null,
  15. };
  16. this.isSetBeforeunloadEventHandler = false;
  17. this.initDrafts();
  18. }
  19. /**
  20. * Workaround for the mangling in production build to break constructor.name
  21. */
  22. static getClassName() {
  23. return 'EditorContainer';
  24. }
  25. /**
  26. * initialize state for drafts
  27. */
  28. initDrafts() {
  29. this.drafts = {};
  30. // restore data from localStorage
  31. const contents = window.localStorage.drafts;
  32. if (contents != null) {
  33. try {
  34. this.drafts = JSON.parse(contents);
  35. }
  36. catch (e) {
  37. window.localStorage.removeItem('drafts');
  38. }
  39. }
  40. if (this.state.pageId == null) {
  41. const draft = this.findDraft(this.state.path);
  42. if (draft != null) {
  43. this.state.markdown = draft;
  44. }
  45. }
  46. }
  47. getCurrentOptionsToSave() {
  48. const opt = {
  49. pageTags: this.state.tags,
  50. };
  51. return opt;
  52. }
  53. // See https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#example
  54. showUnsavedWarning(e) {
  55. // Cancel the event
  56. e.preventDefault();
  57. // display browser default message
  58. e.returnValue = '';
  59. return '';
  60. }
  61. disableUnsavedWarning() {
  62. window.removeEventListener('beforeunload', this.showUnsavedWarning);
  63. this.isSetBeforeunloadEventHandler = false;
  64. }
  65. enableUnsavedWarning() {
  66. if (!this.isSetBeforeunloadEventHandler) {
  67. window.addEventListener('beforeunload', this.showUnsavedWarning);
  68. this.isSetBeforeunloadEventHandler = true;
  69. }
  70. }
  71. clearDraft(path) {
  72. delete this.drafts[path];
  73. window.localStorage.setItem('drafts', JSON.stringify(this.drafts));
  74. }
  75. clearAllDrafts() {
  76. window.localStorage.removeItem('drafts');
  77. }
  78. saveDraft(path, body) {
  79. this.drafts[path] = body;
  80. window.localStorage.setItem('drafts', JSON.stringify(this.drafts));
  81. }
  82. findDraft(path) {
  83. if (this.drafts != null && this.drafts[path]) {
  84. return this.drafts[path];
  85. }
  86. return null;
  87. }
  88. }