<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { useScroll } from "@vueuse/core";

const props = defineProps<{
  map: Map<string, any>;
}>();

const scrollElement = ref<HTMLElement | null>(null);
const { y: scrollTop } = useScroll(scrollElement);

onMounted(() => {
  scrollElement.value = document.getElementsByClassName(
    "el-scrollbar__wrap"
  )[1] as HTMLElement;
});

function toDetailPosition(title: string) {
  const { top } = props.map.get(title);
  scrollElement.value.scrollTo({ top: Number(top) });
}

//锚点的激活状态
function isActive(title: string) {
  let nextTop = 0;
  let prevTop = 0;
  const entries = [...props.map.entries()];
  const { top: currentTop, index: currentIndex } = props.map.get(title);

  entries.forEach(([_, { index, top }]) => {
    const isNext = currentIndex + 1 === index;
    const isPrev = currentIndex - 1 === index;
    if (isNext) nextTop = top;
    if (isPrev) prevTop = top;
  });

  if (currentIndex === 0)
    return scrollTop.value >= 0 && scrollTop.value < nextTop;

  return (
    scrollTop.value > prevTop &&
    scrollTop.value < nextTop &&
    scrollTop.value >= currentTop
  );
}
</script>

<template>
  <ul fixed p-5 text-sm font-bold>
    <li
      class="hover:text-blue hover:bg-#f7f7f7 cursor-pointer duration-200ms p-1.5 m-1 rounded"
      :class="{ 'is-active': isActive(title) }"
      v-for="([title], index) in map.entries()"
      @click="() => toDetailPosition(title)"
      :key="index"
    >
      {{ title }}
    </li>
  </ul>
</template>

<style lang="scss" scoped>
.is-active {
  color: rgba(96, 165, 250, 0.9);
  background-color: #f7f7f7;
}
</style>
