Skip to content

estimateArrivalTimes GraphQLクエリを叩くカスタムフックを追加 - #6320

Merged
TinyKitten merged 7 commits into
devfrom
feature/estimate-arrival-times
Jul 1, 2026
Merged

TinyKitten merged 7 commits into
devfrom
feature/estimate-arrival-times

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

概要

estimateArrivalTimes GraphQL クエリを呼び出すカスタムフック useEstimateArrivalTimes を追加。始発駅〜終着駅間の経由路線 ID を渡し、レスポンスの routes を列車種別の groupId(種別指定時)または選択中の路線 ID でフィルタリングして返す。

変更の種類

  • バグ修正
  • 新機能
  • リファクタリング
  • ドキュメント
  • CI/CD
  • その他

変更内容

  • src/lib/graphql/queries.ts: ESTIMATE_ARRIVAL_TIMES クエリ定義を追加
  • src/@types/graphql.d.ts: EstimatedArrivalStop / EstimatedArrivalRoute / EstimatedArrivalPage 型、Query.estimateArrivalTimes フィールド、オペレーション型を追加
  • src/hooks/useEstimateArrivalTimes.ts: 新規カスタムフック
    • stations 配列から fromStationId・toStationId・viaLineIds(重複排除した全路線 ID)を算出
    • selectedDirection に応じて fromStationId / toStationId の前後を切り替え(OUTBOUND: 末尾→先頭、INBOUND: 先頭→末尾)
    • filteringId(trainType.groupId ?? selectedLine.id)を skip 条件に含め、フィルタ先が無い場合の不要なフェッチを防止
    • useCurrentTrainType() が非 null なら routes.id === groupId、null なら routes.id === selectedLine.id でフィルタリング
    • docstring・コード内コメントを追加
  • src/hooks/useEstimateArrivalTimes.test.tsx: 単体テスト(skip 条件、方向切り替え、フィルタリング、viaLineIds 重複排除など 8 ケース)

テスト

  • npm run lint が通ること
  • npm test が通ること
  • npm run typecheck が通ること

関連Issue

スクリーンショット(任意)

Summary by CodeRabbit

  • 新機能
    • 駅間の推定到着時刻を取得・表示できるようになりました。
    • 選択中の駅・路線・方向(必要に応じて現在の車種)に合う到着ルートを自動で絞り込みます。
    • 条件がそろっていない場合は予測取得を行いません。
  • テスト
    • 条件分岐、ルートの絞り込み、経由路線指定、到着時刻の相対化と除外処理を検証するテストを追加しました。

@TinyKitten TinyKitten self-assigned this Jun 30, 2026
@github-actions github-actions Bot added the react label Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

GraphQLの推定到着時刻用型とクエリを追加し、それを利用するuseEstimateArrivalTimesフックと再エクスポート、検証テストを追加しました。フックは選択中の駅・路線情報から検索条件を組み立て、取得結果から一致するルートを整形して返します。

Changes

推定到着時刻取得機能

Layer / File(s) Summary
GraphQL型定義の追加
src/@types/graphql.d.ts
Query型にestimateArrivalTimesを追加し、引数型、レスポンス型、クエリ変数・結果型を新設。
クエリ定義とフックの実装
src/lib/graphql/queries.ts, src/hooks/useEstimateArrivalTimes.ts, src/hooks/index.ts
estimateArrivalTimesクエリを定義し、選択状態から条件を組み立ててGraphQLを実行し、一致するrouteを返すフックを追加して再エクスポート。
useEstimateArrivalTimesのテスト追加
src/hooks/useEstimateArrivalTimes.test.tsx
入力欠落、方向分岐、route選択、到着時刻の相対化、左側駅の絞り込み、viaLineIdsの重複排除をモック付きで検証するテストを追加。

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • TrainLCD/MobileApp#6050: leftStations の生成や順序に関わる変更があり、このPRのフックがその並びを使って到着時刻の区間を切り出す点で接点があります。
  • TrainLCD/MobileApp#6210: 新しい ESTIMATE_ARRIVAL_TIMES クエリと gqlRequest ベースの取得経路が、同じGraphQL通信基盤の変更に依存しています。

Sequence Diagram(s)

sequenceDiagram
  participant useEstimateArrivalTimes
  participant useGraphQLQuery
  participant GraphQLサーバー
  useEstimateArrivalTimes->>useEstimateArrivalTimes: fromStationId/toStationId/viaLineIdsを算出
  useEstimateArrivalTimes->>useGraphQLQuery: ESTIMATE_ARRIVAL_TIMESと変数を渡す
  useGraphQLQuery->>GraphQLサーバー: estimateArrivalTimesクエリ送信
  GraphQLサーバー-->>useGraphQLQuery: EstimatedArrivalPage(routes/stops)
  useGraphQLQuery-->>useEstimateArrivalTimes: data/loading/error
  useEstimateArrivalTimes->>useEstimateArrivalTimes: groupId/selectedLine.idで一致するrouteを検索
  useEstimateArrivalTimes-->>useEstimateArrivalTimes: route/loading/errorを返却
Loading

Poem

ぴょんっと型を増やしたよ、GraphQLの森で
ルートをたどって、stopを数えて
うさぎの耳で一致を探し
ふわっと返す、到着のしるし
今日もぴかりと、前へ進む🐰

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed 主要な変更である estimateArrivalTimes を呼ぶカスタムフック追加を簡潔に表しており、内容と一致しています。
Description check ✅ Passed 概要・変更の種類・変更内容・テストが揃っており、テンプレート要件を概ね満たしています。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/estimate-arrival-times

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
src/hooks/useEstimateArrivalTimes.ts (3)

13-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

フックの責務に関するドキュメント(docstring)が不足しています。

useEstimateArrivalTimes は複数のatom(駅・路線・選択中の境界)とGraphQLクエリ・路線種別フックを組み合わせ、入出力契約({ route, loading, error })を持つロジックを実装していますが、責務や期待される振る舞いを説明するコメントがありません。

短い説明(入力となるatom、skip条件、フィルタリングロジックの意図)を追加すると保守性が向上します。

✏️ 提案: docstringの追加
+/**
+ * 選択中の路線・駅情報から estimateArrivalTimes クエリの変数を組み立て、
+ * 現在の種別 (groupId) または選択中の路線 ID に一致するルートを返すフック。
+ */
 export const useEstimateArrivalTimes = () => {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/hooks/useEstimateArrivalTimes.ts` around lines 13 - 20, Add a concise
docstring to useEstimateArrivalTimes explaining its responsibility: it combines
stationsAtom, selectedBoundAtom, selectedLineAtom, and useCurrentTrainType to
build the route estimate result. Mention the expected contract ({ route,
loading, error }), the skip conditions used by the GraphQL query, and that the
filtering logic narrows results by selected line/bound and train type.

Source: Coding guidelines


13-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

新規フックの単体テストが含まれていません。

コーディングガイドラインでは「振る舞いを変更・追加する場合は同じ変更セット内でテストを追加・更新すること」と定められていますが、本フック(route照合・skipロジックを含む中心的なビジネスロジック)に対するテストファイルが見当たりません。テストをスキップする場合はTODOと担当者の理由を明記する必要があります。

#!/bin/bash
fd 'useEstimateArrivalTimes' --extension test.ts --extension spec.ts
rg -l 'useEstimateArrivalTimes' --glob '*test*' --glob '*spec*'
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/hooks/useEstimateArrivalTimes.ts` around lines 13 - 60, The new
useEstimateArrivalTimes hook adds core route-matching and skip logic, but no
unit tests were added or updated. Add a test file for useEstimateArrivalTimes
that covers skip behavior when selectedBound/fromStationId/toStationId are
missing, and route selection based on trainType.groupId or selectedLine.id using
the hook’s matchedRoute logic and useGraphQLQuery results. If tests are
intentionally omitted, add a TODO with the responsible owner and reason in the
same change set.

Source: Coding guidelines


31-43: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

skip条件にフィルタリング対象IDの有無を含めることでムダなフェッチを避けられます。

skip は selectedBound・fromStationId・toStationId のみを見ており、trainType?.groupId と selectedLine?.id が両方とも null の場合(45-54行のロジックにより matchedRoute は常に null になる)でもクエリは実行されてしまいます。filteringId の計算を skip に含めることで、結果が使われないリクエストを未然に防げます。

♻️ 提案: filteringId をskip条件に含める
-  const skip = !selectedBound || fromStationId == null || toStationId == null;
+  const filteringId = trainType?.groupId ?? selectedLine?.id;
+  const skip =
+    !selectedBound ||
+    fromStationId == null ||
+    toStationId == null ||
+    filteringId == null;

(その場合、45-54行の matchedRoute 内の filteringId 計算と重複するため、上位の値を再利用するよう調整してください。)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/hooks/useEstimateArrivalTimes.ts` around lines 31 - 43,
useEstimateArrivalTimes の skip 条件が selectedBound/fromStationId/toStationId
しか見ておらず、trainType?.groupId と selectedLine?.id が両方 null
の場合でも不要なクエリが走っています。filteringId を先に計算して、その有無も skip に含めて ESTIMATE_ARRIVAL_TIMES
のフェッチを止めてください。あわせて matchedRoute 側で同じ filteringId
を再計算しないよう、上位で算出した値を再利用する形に調整してください。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/hooks/useEstimateArrivalTimes.ts`:
- Around line 13-20: Add a concise docstring to useEstimateArrivalTimes
explaining its responsibility: it combines stationsAtom, selectedBoundAtom,
selectedLineAtom, and useCurrentTrainType to build the route estimate result.
Mention the expected contract ({ route, loading, error }), the skip conditions
used by the GraphQL query, and that the filtering logic narrows results by
selected line/bound and train type.
- Around line 13-60: The new useEstimateArrivalTimes hook adds core
route-matching and skip logic, but no unit tests were added or updated. Add a
test file for useEstimateArrivalTimes that covers skip behavior when
selectedBound/fromStationId/toStationId are missing, and route selection based
on trainType.groupId or selectedLine.id using the hook’s matchedRoute logic and
useGraphQLQuery results. If tests are intentionally omitted, add a TODO with the
responsible owner and reason in the same change set.
- Around line 31-43: useEstimateArrivalTimes の skip 条件が
selectedBound/fromStationId/toStationId しか見ておらず、trainType?.groupId と
selectedLine?.id が両方 null の場合でも不要なクエリが走っています。filteringId を先に計算して、その有無も skip に含めて
ESTIMATE_ARRIVAL_TIMES のフェッチを止めてください。あわせて matchedRoute 側で同じ filteringId
を再計算しないよう、上位で算出した値を再利用する形に調整してください。

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f23b98ad-9e45-4e70-bdb0-97f9619e9ce7

📥 Commits

Reviewing files that changed from the base of the PR and between d432f3c and f9f1814.

📒 Files selected for processing (3)
  • src/@types/graphql.d.ts
  • src/hooks/useEstimateArrivalTimes.ts
  • src/lib/graphql/queries.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/hooks/useEstimateArrivalTimes.test.tsx`:
- Around line 79-84: Biome formatting is out of sync in
useEstimateArrivalTimes.test.tsx, so update the affected test setup block to
match the formatter output. Re-run the file through the Biome formatter and
commit the resulting whitespace/line-break changes around the mock declarations
for useAtomValue, useCurrentTrainType, and gqlRequest so the CI format check
passes.
- Around line 241-246: The Biome formatter is flagging a style mismatch in the
assertion block inside useEstimateArrivalTimes test, so update the formatting to
match the formatter’s output and commit the regenerated diff. Check the mocked
variables assertions around mockGqlRequest.mock.calls and keep the
expect(...).toEqual(...) call in the exact single-line form Biome produces when
it fits within the line length, then re-run formatting so the test file matches
CI.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cf5d71ce-cd25-4e89-ab10-b73e65dc5957

📥 Commits

Reviewing files that changed from the base of the PR and between 864300c and 1f79b31.

📒 Files selected for processing (2)
  • src/hooks/useEstimateArrivalTimes.test.tsx
  • src/hooks/useEstimateArrivalTimes.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/hooks/useEstimateArrivalTimes.ts

@TinyKitten

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@TinyKitten

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/hooks/useEstimateArrivalTimes.ts (1)

36-39: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

selectedDirection 未確定時はクエリを skip してください。

Line 36-39 は null など OUTBOUND 以外をすべて INBOUND 扱いにするため、selectedBound が残った状態で selectedDirection だけ未確定だと誤った from/to で取得します。INBOUND も明示分岐し、未確定時は skip してください。

修正案
   const fromStationId =
-    selectedDirection === 'OUTBOUND' ? stations.at(-1)?.id : stations[0]?.id;
+    selectedDirection === 'OUTBOUND'
+      ? stations.at(-1)?.id
+      : selectedDirection === 'INBOUND'
+        ? stations[0]?.id
+        : undefined;
   const toStationId =
-    selectedDirection === 'OUTBOUND' ? stations[0]?.id : stations.at(-1)?.id;
+    selectedDirection === 'OUTBOUND'
+      ? stations[0]?.id
+      : selectedDirection === 'INBOUND'
+        ? stations.at(-1)?.id
+        : undefined;
   const skip =
     !selectedBound ||
+    selectedDirection == null ||
     fromStationId == null ||
     toStationId == null ||
     filteringId == null;

Also applies to: 55-59

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/hooks/useEstimateArrivalTimes.ts` around lines 36 - 39,
`useEstimateArrivalTimes` is treating any non-OUTBOUND `selectedDirection` as
INBOUND, so when the direction is still unset it builds the wrong from/to
station IDs and still runs the query. Update the `useEstimateArrivalTimes` logic
to explicitly branch on `selectedDirection` in the station-id selection and use
`skip` until the direction is definitively OUTBOUND or INBOUND; apply the same
guard to the query setup referenced by the later affected block as well.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/hooks/useEstimateArrivalTimes.ts`:
- Around line 131-135: The relative-time base selection in
useEstimateArrivalTimes currently only checks windowStops for the current
station, so when the current station is outside the window it falls back to raw
minutes. Update the baseMinutes logic to also consider the current station stop
from allStops, using the stop immediately before the visible window as a
fallback base candidate when windowStops does not contain
currentStation?.groupId. Keep the existing behavior for window-contained
stations, but ensure the current station is still used as the reference point
even when it is outside leftStations.

---

Outside diff comments:
In `@src/hooks/useEstimateArrivalTimes.ts`:
- Around line 36-39: `useEstimateArrivalTimes` is treating any non-OUTBOUND
`selectedDirection` as INBOUND, so when the direction is still unset it builds
the wrong from/to station IDs and still runs the query. Update the
`useEstimateArrivalTimes` logic to explicitly branch on `selectedDirection` in
the station-id selection and use `skip` until the direction is definitively
OUTBOUND or INBOUND; apply the same guard to the query setup referenced by the
later affected block as well.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 810292d4-8b39-4734-b7ec-91d4d2c31bc9

📥 Commits

Reviewing files that changed from the base of the PR and between 8681276 and 1d6c3b2.

📒 Files selected for processing (3)
  • src/hooks/index.ts
  • src/hooks/useEstimateArrivalTimes.test.tsx
  • src/hooks/useEstimateArrivalTimes.ts

Comment thread src/hooks/useEstimateArrivalTimes.ts Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant