<template>
  <div class="rich-text-container" :class="{ error: isError }">
    <div class="header">
      <Button class="add-button" @click.native="add" size="small"
        >{{ t("survey_creator.question.rich_text.filler") }}
      </Button>
    </div>
    <div
      class="rich-text-area"
      ref="richTextArea"
      contenteditable="true"
      :placeholder="placeholder"
      @input="onInput"
    />
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { Button } from "view-design";
import { t } from "../../../locale";

export default Vue.extend({
  name: "rich-text",
  components: { Button },
  props: {
    value: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      spaceCharacter: "_____",
      isError: false,
    };
  },
  mounted() {
    this.$nextTick(() => {
      if (this.value) {
        this.$refs.richTextArea.innerText = this.value;
      }
    });
  },
  methods: {
    t,
    replaceNewline(str) {
      return str.replace(/(\n|\r|\r\n)/g, "");
    },
    add() {
      const div = this.$refs.richTextArea;
      div.focus();
      const sel = window.getSelection();
      if (sel) {
        const range = sel.getRangeAt(0);
        const el = document.createElement("span");
        el.innerText = this.spaceCharacter;
        range.insertNode(el);
        range.collapse(false);
      }
      this.$emit("input", this.replaceNewline(div.innerText));
    },
    onInput(e) {
      this.$emit("input", this.replaceNewline(e.target.innerText));
    },
    onValidate(valid) {
      this.isError = valid;
    },
  },
});
</script>

<style lang="less" scoped>
.rich-text-container {
  display: flex;
  flex-direction: column;
  border-radius: 4px;
  outline: 1px solid #dcdee2;

  &:focus-within {
    outline: 1px solid #1890ff;
  }

  .header {
    height: 40px;
    display: flex;
    align-items: center;
    background-color: #f7f7f7;

    .add-button {
      margin-left: 8px;
      color: #1890ff;
      border-color: #1890ff;
    }
  }

  .rich-text-area {
    width: 100%;
    overflow: auto;
    padding: 5px;
    outline: none;
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    &:empty:after {
      content: attr(placeholder);
      color: #c5c8ce;
    }
  }
}

.error {
  outline-color: #ed4014;
}
</style>
