index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import React from 'react';
  2. import Editor from '@components/Base/Editor';
  3. import {
  4. EDITOR_EVENTS,
  5. EDITOR_REACT_EVENTS,
  6. EVENT_BEFORE_ADD_PAGE,
  7. EVENT_AFTER_ADD_PAGE,
  8. } from '@common/constants';
  9. import { pick } from '@utils';
  10. import Global from '@common/Global';
  11. import GGEditorContext from '@common/context/GGEditorContext';
  12. import PropsAPIContext from '@common/context/PropsAPIContext';
  13. import PropsAPI from '@common/context/PropsAPIContext/propsAPI';
  14. class GGEditor extends React.Component {
  15. static setTrackable(value) {
  16. Global.set('trackable', Boolean(value));
  17. }
  18. editor = null;
  19. get currentPage() {
  20. return this.editor.getCurrentPage();
  21. }
  22. constructor(props) {
  23. super(props);
  24. this.init();
  25. this.bindEvent();
  26. }
  27. addListener = (target, eventName, handler) => {
  28. if (typeof handler === 'function') target.on(eventName, handler);
  29. };
  30. handleBeforeAddPage = (func) => {
  31. this.editor.on(EVENT_BEFORE_ADD_PAGE, func);
  32. };
  33. handleAfterAddPage = (func) => {
  34. const { currentPage: page } = this;
  35. if (page) {
  36. func({ page });
  37. return;
  38. }
  39. this.editor.on(EVENT_AFTER_ADD_PAGE, func);
  40. };
  41. init() {
  42. this.editor = new Editor();
  43. this.ggEditor = {
  44. editor: this.editor,
  45. onBeforeAddPage: this.handleBeforeAddPage,
  46. onAfterAddPage: this.handleAfterAddPage,
  47. };
  48. this.propsAPI = new PropsAPI(this.editor);
  49. }
  50. bindEvent() {
  51. EDITOR_EVENTS.forEach((event) => {
  52. this.addListener(this.editor, [event], this.props[EDITOR_REACT_EVENTS[event]]);
  53. });
  54. }
  55. componentWillUnmount() {
  56. this.editor.destroy();
  57. }
  58. render() {
  59. const { children } = this.props;
  60. return (
  61. <GGEditorContext.Provider value={this.ggEditor}>
  62. <PropsAPIContext.Provider value={this.propsAPI}>
  63. <div {...pick(this.props, ['style', 'className'])}>{children}</div>
  64. </PropsAPIContext.Provider>
  65. </GGEditorContext.Provider>
  66. );
  67. }
  68. }
  69. export default GGEditor;