EditorContainer.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { Container } from 'unstated';
  2. import loggerFactory from '~/utils/logger';
  3. const logger = loggerFactory('growi:services:EditorContainer');
  4. /*
  5. * TODO: Omit Unstated: EditorContainer
  6. * => https://redmine.weseek.co.jp/issues/103246
  7. */
  8. /**
  9. * Service container related to options for Editor/Preview
  10. * @extends {Container} unstated Container
  11. */
  12. export default class EditorContainer extends Container {
  13. constructor(appContainer) {
  14. super();
  15. this.appContainer = appContainer;
  16. this.appContainer.registerContainer(this);
  17. this.state = {
  18. tags: null,
  19. };
  20. this.initDrafts();
  21. }
  22. /**
  23. * Workaround for the mangling in production build to break constructor.name
  24. */
  25. static getClassName() {
  26. return 'EditorContainer';
  27. }
  28. /**
  29. * initialize state for drafts
  30. */
  31. initDrafts() {
  32. this.drafts = {};
  33. // restore data from localStorage
  34. const contents = window.localStorage.drafts;
  35. if (contents != null) {
  36. try {
  37. this.drafts = JSON.parse(contents);
  38. }
  39. catch (e) {
  40. window.localStorage.removeItem('drafts');
  41. }
  42. }
  43. if (this.state.pageId == null) {
  44. const draft = this.findDraft(this.state.path);
  45. if (draft != null) {
  46. this.state.markdown = draft;
  47. }
  48. }
  49. }
  50. clearDraft(path) {
  51. delete this.drafts[path];
  52. window.localStorage.setItem('drafts', JSON.stringify(this.drafts));
  53. }
  54. clearAllDrafts() {
  55. window.localStorage.removeItem('drafts');
  56. }
  57. saveDraft(path, body) {
  58. this.drafts[path] = body;
  59. window.localStorage.setItem('drafts', JSON.stringify(this.drafts));
  60. }
  61. findDraft(path) {
  62. if (this.drafts != null && this.drafts[path]) {
  63. return this.drafts[path];
  64. }
  65. return null;
  66. }
  67. }