<template>
  <div>
    <VMenu />
    <div
      :id="'ved' + _uid"
      ref="editor"
      class="v-editor"
      :data-placeholder="placeholder"
      contenteditable
      @blur="emitJSON"
    ></div>
  </div>
</template>

<script>
import VMenu from "./components/VMenu.vue";
import { renderRichText } from "./renderJSON";
import { toJSON } from "./toJSON";

export default {
  name: "VEditor",
  components: {
    VMenu,
  },
  props: {
    placeholder: { type: String, default: "请输入..." },
    value: {
      type: String,
      default: () => `{}`,
    },
  },
  watch: {
    value() {
      renderRichText(JSON.parse(this.value), this.$refs.editor);
    },
  },
  mounted() {
    renderRichText(JSON.parse(this.value), this.$refs.editor);

    this.$refs.editor.addEventListener("paste", (event) => {
      event.preventDefault();
      let pasteText = (event.clipboardData || window.clipboardData).getData(
        "text"
      );
      document.execCommand("insertText", false, pasteText);
    });
  },
  methods: {
    emitJSON() {
      if (this.$refs.editor.contentEditable) {
        const json = toJSON(this.$refs.editor);
        // this.$emit("input", json);
        // this.$emit("change", json);
        this.$emit("result", json);
      }
    },
  },
};
</script>

<style>
.v-editor,
.sourceView {
  border: 1px solid grey;
  border-radius: 5px;
  height: 300px;
  padding: 5px;
  overflow: scroll;
}

.sourceView {
  margin: -5px;
}

.v-editor[contenteditable="true"]:empty:not(:focus)::before {
  content: attr(data-placeholder);
}
</style>
