@@ -13,31 +13,44 @@ const ANSWERS = {
1313}
1414
1515function App ( ) {
16- // 現在の問題番号
1716 const [ step , setStep ] = useState ( 1 )
18- // 判定結果
1917 const [ result , setResult ] = useState < CheckResult | null > ( null )
2018 const [ error , setError ] = useState < string | null > ( null )
2119
22- // イベントリスナー内で最新の step を参照するための Ref
2320 const stepRef = useRef ( step )
24- // 各ステップの初期値を保持するベースライン
2521 const baselineRef = useRef < { p1 : string | null ; p2 : string | null ; p3Visible : boolean | null ; p4 : string | null } > ( {
2622 p1 : null ,
2723 p2 : null ,
2824 p3Visible : null ,
2925 p4 : null ,
3026 } )
27+ const pageKeyRef = useRef < string | null > ( null )
28+
29+ // 追加: ステップの永続化
30+ useEffect ( ( ) => {
31+ chrome . storage . local . get ( [ 'currentStep' ] ) . then ( ( { currentStep } ) => {
32+ if ( typeof currentStep === 'number' ) {
33+ setStep ( currentStep )
34+ stepRef . current = currentStep
35+ }
36+ } )
37+ } , [ ] )
38+
39+ useEffect ( ( ) => {
40+ chrome . storage . local . set ( { currentStep : step } )
41+ } , [ step ] )
3142
32- // state が変わったら ref も更新しておく
43+ // イベントリスナー内で最新の step を参照するための Ref
3344 useEffect ( ( ) => {
3445 stepRef . current = step
3546 } , [ step ] )
3647
3748 useEffect ( ( ) => {
49+ let disposed = false
3850 let port : chrome . runtime . Port | null = null
3951
4052 const connect = async ( ) => {
53+ if ( disposed ) return
4154 try {
4255 const [ tab ] = await chrome . tabs . query ( { active : true , currentWindow : true } )
4356 if ( ! tab ?. id ) return
@@ -49,6 +62,12 @@ function App() {
4962 const { p1, p2, p3Visible, p4 } = msg . values
5063 const currentStep = stepRef . current
5164
65+ if ( msg . pageKey !== pageKeyRef . current ) {
66+ pageKeyRef . current = msg . pageKey ?? null
67+ baselineRef . current = { p1 : null , p2 : null , p3Visible : null , p4 : null }
68+ setResult ( null )
69+ }
70+
5271 if ( currentStep === 1 ) {
5372 // 初回メッセージでベースラインを記録
5473 if ( baselineRef . current . p1 === null ) {
@@ -109,9 +128,12 @@ function App() {
109128
110129 port . onDisconnect . addListener ( ( ) => {
111130 baselineRef . current = { p1 : null , p2 : null , p3Visible : null , p4 : null }
131+ pageKeyRef . current = null
112132 port = null
113133 setResult ( null )
114- setStep ( 1 )
134+ if ( ! disposed ) {
135+ setTimeout ( connect , 200 )
136+ }
115137 } )
116138 } catch ( e : any ) {
117139 setError ( e ?. message ?? String ( e ) )
@@ -121,6 +143,7 @@ function App() {
121143 connect ( )
122144
123145 return ( ) => {
146+ disposed = true
124147 if ( port ) {
125148 try { port . disconnect ( ) } catch { }
126149 }
0 commit comments