<template>
  <div class="row">
    <div class="ten wide column">
      <h1>{{ flatpage.title }}</h1>
      <div v-html="flatpage.content"></div>

      <div class="ui right rail">
        <div id="toc-container" class="ui sticky fixed">
          <h4 class="ui header">Table des matières</h4>
          <div id="page-toc" class="ui vertical large text menu">
            <a
              v-for="h2 in sections"
              :key="h2.id"
              class="item"
              :href="'#' + h2.id"
              >{{ h2.text }}</a
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "With_right_menu",

  data() {
    return {
      sections: [],
    };
  },

  computed: {
    ...mapState(["staticPages"]),
    flatpage() {
      if (this.staticPages) {
        return this.staticPages.find(
          (page) => page.url === `/${this.$route.name}/`
        );
      }
      return null;
    },
  },

  methods: {
    createMenu() {
      // parse the ToC content (looking for h2 elements)
      let list = document.querySelectorAll("h2");
      let tocArr = [];

      for (let i = 0; i < list.length; i++) {
        let e = list[i];
        let id = e.id;

        // add id in html if not present
        if (id === "") {
          id = "toc-id-" + i;
          e.id = id;
        }

        tocArr.push({
          text: e.textContent,
          id: id,
        });
      }
      this.sections = tocArr;
    },
  },
  mounted() {
    this.$nextTick(() => {
      // The whole view is rendered, so we can safely access or query the DOM.
      this.createMenu();
    });
  },
};
</script>