Skip to content

Commit cfb6f22

Browse files
add find by url option
1 parent 3f1d8be commit cfb6f22

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

src/components/question-node.tsx

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"use client"
22

3-
import { useState } from "react"
3+
import { useState, useEffect } from "react"
44
import { motion, AnimatePresence } from "framer-motion"
55

66
const POSITIVE_RESPONSES = [
@@ -37,6 +37,36 @@ interface Node {
3737
link?: string
3838
}
3939

40+
const findNodeById = (node: Node, id: string): { currentNode: Node, parentNode: Node | null, optionIndex: number } | null => {
41+
if (node.options) {
42+
const directOptionIndex = node.options.findIndex(option => option.id === id)
43+
if (directOptionIndex !== -1) {
44+
const targetNode = node.options[directOptionIndex]
45+
if (targetNode.options) {
46+
return {
47+
currentNode: targetNode,
48+
parentNode: node,
49+
optionIndex: 0
50+
}
51+
}
52+
return {
53+
currentNode: node,
54+
parentNode: null,
55+
optionIndex: directOptionIndex
56+
}
57+
}
58+
59+
for (const option of node.options) {
60+
if (option.options) {
61+
const found = findNodeById(option, id)
62+
if (found) return found
63+
}
64+
}
65+
}
66+
67+
return null
68+
}
69+
4070
export function QuestionNode({ node }: { node: Node }) {
4171
const [currentNode, setCurrentNode] = useState(node)
4272
const [optionIndex, setOptionIndex] = useState(0)
@@ -49,6 +79,18 @@ export function QuestionNode({ node }: { node: Node }) {
4979
const isLastOption = currentNode.options && optionIndex + 1 >= currentNode.options.length
5080
const isMainLevel = currentNode === node
5181

82+
useEffect(() => {
83+
const hash = window.location.hash.slice(1)
84+
if (hash) {
85+
const found = findNodeById(node, hash)
86+
if (found) {
87+
setCurrentNode(found.currentNode)
88+
setParentNode(found.parentNode)
89+
setOptionIndex(found.optionIndex)
90+
}
91+
}
92+
}, [node])
93+
5294
return (
5395
<div className="space-y-8">
5496
<AnimatePresence mode="wait">

0 commit comments

Comments
 (0)