summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/content_editor/components/editor_state_observer.vue
blob: 41c3771bf41691f3ecebb7b74f5c1b4dce1e3795 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<script>
import { debounce } from 'lodash';
import { ALERT_EVENT } from '../constants';

export const tiptapToComponentMap = {
  update: 'docUpdate',
  selectionUpdate: 'selectionUpdate',
  transaction: 'transaction',
  focus: 'focus',
  blur: 'blur',
};

export const eventHubEvents = [ALERT_EVENT];

const getComponentEventName = (tiptapEventName) => tiptapToComponentMap[tiptapEventName];

export default {
  inject: ['tiptapEditor', 'eventHub'],
  created() {
    this.disposables = [];

    Object.keys(tiptapToComponentMap).forEach((tiptapEvent) => {
      const eventHandler = debounce(
        (params) => this.bubbleEvent(getComponentEventName(tiptapEvent), params),
        100,
      );

      this.tiptapEditor?.on(tiptapEvent, eventHandler);

      this.disposables.push(() => this.tiptapEditor?.off(tiptapEvent, eventHandler));
    });

    eventHubEvents.forEach((event) => {
      const handler = (...params) => {
        this.bubbleEvent(event, ...params);
      };

      this.eventHub.$on(event, handler);
      this.disposables.push(() => this.eventHub?.$off(event, handler));
    });
  },
  beforeDestroy() {
    this.disposables.forEach((dispose) => dispose());
  },
  methods: {
    bubbleEvent(eventHubEvent, params) {
      this.$emit(eventHubEvent, params);
    },
  },
  render() {
    return this.$scopedSlots.default?.();
  },
};
</script>