Files
ko-grammar/docs/.vitepress/theme/components/SentenceQuiz.vue
T
2026-04-28 15:41:18 +07:00

74 lines
1.6 KiB
Vue

<template>
<div id="sentence-quiz" :class="$style.root" ref="main">
<button type="button" @click="nextSentence()">Next</button>
<slot />
</div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, useTemplateRef } from "vue";
const mainEl = useTemplateRef("main");
const sentences = ref<number[]>([]);
const sentences_array_index = ref(NaN);
function nextSentence() {
if (!mainEl.value) return;
const getCurrentSentenceIndex = () => {
if (sentences.value.length <= 1) {
return 0;
}
if (++sentences_array_index.value < sentences.value.length) {
return sentences.value[sentences_array_index.value];
}
sentences.value = sentences.value
.map((s) => ({ s, k: Math.random() }))
.sort((a, b) => a.k - b.k)
.map((a) => a.s);
sentences_array_index.value = 0;
return sentences.value[sentences_array_index.value];
};
const currentSentenceIndex = getCurrentSentenceIndex();
mainEl.value.querySelectorAll("#sentence-quiz > ul > li").forEach((el, i) => {
if (!(el instanceof HTMLElement)) return;
el.style.display = i === currentSentenceIndex ? "" : "none";
});
}
onMounted(() => {
nextTick(() => {
if (!mainEl.value) return;
sentences.value = Array.from(
mainEl.value.querySelectorAll("#sentence-quiz > ul > li"),
).map((el, i) => i);
nextSentence();
});
});
</script>
<style module>
.root {
margin-top: 1em;
&:hover li li {
display: none;
}
> button {
float: right;
border: 1px solid gray;
padding: 0 0.5em;
border-radius: 5px;
}
}
</style>