import { computed, ref } from "vue";
interface NavigationOptions {
totalQuestions: () => number;
}
const SUBMIT_OPTION_COUNT = 3;
/**
* 负责题目与选项的导航状态,便于键盘与按钮复用同一套逻辑。
*/
export function useNavigation(options: NavigationOptions) {
const currentQuestionIndex = ref(0);
const currentOptionIndex = ref(0);
const previousQuestionIndex = ref(0);
const questionTransition = computed(() => {
return previousQuestionIndex.value < currentQuestionIndex.value
? "slide-left"
: "slide-right";
});
const isOnSubmitStep = computed(() => {
return currentQuestionIndex.value === options.totalQuestions();
});
function navigateToQuestion(index: number) {
const maxIndex = options.totalQuestions();
previousQuestionIndex.value = currentQuestionIndex.value;
currentQuestionIndex.value = Math.max(0, Math.min(index, maxIndex));
currentOptionIndex.value = 0;
}
function navigateQuestions(direction: "prev" | "next") {
const delta = direction === "next" ? 1 : -1;
navigateToQuestion(currentQuestionIndex.value + delta);
}
function navigateOptions(
direction: "up" | "down",
optionCount: number,
) {
const delta = direction === "down" ? 1 : -1;
const total = isOnSubmitStep.value ? SUBMIT_OPTION_COUNT : optionCount;
if (total <= 0) return;
currentOptionIndex.value =
(currentOptionIndex.value + delta + total) % total;
}
function setOptionIndex(index: number) {
currentOptionIndex.value = index;
}
return {
currentQuestionIndex,
currentOptionIndex,
previousQuestionIndex,
questionTransition,
isOnSubmitStep,
navigateToQuestion,
navigateQuestions,
navigateOptions,
setOptionIndex,
};
}