Skip to content

ディープリンクで他路線直通の経路全体を sids パラメータで表現できるようにする - #6003

Merged
TinyKitten merged 3 commits into
devfrom
feature/deep-link-multi-line-route
May 16, 2026
Merged

TinyKitten merged 3 commits into
devfrom
feature/deep-link-multi-line-route

Conversation

@TinyKitten

@TinyKitten TinyKitten commented May 16, 2026 •

Copy link
Copy Markdown
Member

概要

ディープリンクで他路線直通・経路全体を表現できるようにする。新パラメータ sids (Station ID のカンマ区切りリスト) を追加し、列挙された駅列の順序通りに stationState.stations を投入する。既存の sgid / lid / lgid ベースのリンクは動作変化なし。

変更の種類

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

変更内容

  • src/lib/graphql/queries.ts: GET_STATIONS_BY_IDS クエリ (stations(ids: [Int!]!)) を追加
  • src/hooks/useDeepLink.ts:
    • handleUrl に sids パラメータの分岐を追加。sids がある場合は sgid / lid / lgid を無視
    • 新規ヘルパー openRouteByStationIds を追加し、駅 ID 配列を順序保持で取得→stationState.stations に投入。selectedLine は先頭駅の .line から直接取得 (各 Station 行で路線が一意に決まるため、隣接関係から推定する必要なし)
    • dir に応じて selectedBound を末尾 (INBOUND) / 先頭 (OUTBOUND) に振り分け
    • isLoading / error 集約に新フェッチを追加
  • src/hooks/useDeepLink.test.tsx: sids ベースのテストを 6 件追加 (順序保持・dir=1 の bound 切替・1 件以下で no-op・解決結果ゼロで no-op・sgid/lid/lgid 無視・auto/theme 併用)

テスト

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

npx jest --testPathPattern=useDeepLink で 20/20 テスト pass を確認。

関連Issue

Closes #6002

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

Summary by CodeRabbit

  • New Features

    • ディープリンクで複数ステーションIDを指定できるようになりました。指定順を保持して経路を再現し、古い識別子は無視されます。ID指定時にテーマ適用や自動モードの反映も行われます。
    • 無効なIDや件数不足、解決結果が空、または不正トークンの場合は状態を変更しない安全な挙動を導入しました。
  • Tests

    • 新ルートや境界条件(選択方向、テーマ/自動モード併用、無効トークン等)を検証するテストを追加しました。

Review Change Stack

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

coderabbitai Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

ディープリンクの新パラメータ sids を受け取り、stations(ids) で複数駅を取得して要求順で state を構築する経路を useDeepLink に追加。GraphQL クエリ、Hook の型・実装、URL 解析分岐、テスト群を統合。既存の sgid/lid 形式はフォールバックで維持。

Changes

駅 ID ベースディープリンク解決の実装

Layer / File(s) Summary
複数駅取得 GraphQL クエリ定義
src/lib/graphql/queries.ts
GET_STATIONS_BY_IDS を追加。$ids: [Int!]! を受け stations(ids: $ids) で複数駅を取得し StationFields を適用。
useDeepLink の型定義と初期化
src/hooks/useDeepLink.ts
GET_STATIONS_BY_IDS を参照し、GetStationsByIdsData/GetStationsByIdsVariables を定義。useLazyQuery(fetchStationsByIds)を初期化してローディング/エラー状態を取得し、戻り値の isLoading/error 集約に組み込んだ。
駅 ID ベースルートオープン処理
src/hooks/useDeepLink.ts
openRouteByStationIds コールバックを追加。取得した駅をディープリンク指定順に並べ替え、選択駅・選択線・方向・自動モード・テーマを設定して navigateToMain する処理を実装。取得空や先頭駅の line 欠落は早期 return。
ディープリンク URL パラメータ解析と分岐
src/hooks/useDeepLink.ts
handleUrl を拡張し sids を優先処理。カンマ区切りトークンを厳密な正の整数として検証(2件以上)し数値化、dir を 0/1 または未指定時のデフォルトで解釈して openRouteByStationIds に委譲。sids がない場合は既存の sgid/lid 経路へフォールバック。useCallback の依存配列を更新。
テスト: setupQueries 拡張と sids テストケース
src/hooks/useDeepLink.test.tsx
setupQueries を拡張して ids 経路を追加。sids 指定時の挙動(要求順での stations 構築、legacy クエリ呼び出し抑止、dir による selectedBound、最小件数/不正トークン/空結果での早期 return、sgid/lid/lgid の無視、auto/theme 併用での設定反映)を検証する複数テストを追加。

Sequence Diagram

sequenceDiagram
  participant User as ユーザー
  participant handleUrl as handleUrl
  participant openRouteByStationIds as openRouteByStationIds
  participant fetchStationsByIds as fetchStationsByIds
  participant StationAPI as Station API
  participant stateAtoms as stateAtoms
  participant navigateToMain as navigateToMain

  User->>handleUrl: sids パラメータ付き URL
  handleUrl->>handleUrl: sids をパース(カンマ区切り→整数配列)
  handleUrl->>openRouteByStationIds: sids、dir、auto、theme を渡す
  openRouteByStationIds->>stateAtoms: theme を反映(themePreference 設定)
  openRouteByStationIds->>fetchStationsByIds: station IDs で複数駅取得
  fetchStationsByIds->>StationAPI: stations(ids: $sids) GraphQL クエリ
  StationAPI-->>fetchStationsByIds: 駅リスト(順序がサーバー都合で異なる可能性)
  openRouteByStationIds->>openRouteByStationIds: 取得駅をリクエスト順に並び替え
  openRouteByStationIds->>stateAtoms: 駅列・選択線・方向・自動モード更新
  openRouteByStationIds->>navigateToMain: メイン画面へ遷移
  navigateToMain-->>User: 駅列を表示
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

駅のIDをつなげてひとつの道筋
サーバーの順番も気にせずに
リクエストの並びがそのまま道しるべ
画面がぱっと開くと私は跳ねる 🐇
小さなリンク、大きな旅路

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed PR タイトルは sids パラメータを使って他路線直通の経路全体をディープリンクで表現できるようにする変更内容を簡潔に説明しており、実装内容と完全に一致しています。
Description check ✅ Passed PR 説明は GitHub テンプレートのすべての主要セクション(概要、変更種類、変更内容、テスト、関連Issue)を網羅しており、変更内容を詳細に記述しており、テスト実行状況を明記しています。
Linked Issues check ✅ Passed 実装内容が #6002 の受け入れ条件をすべて満たしています:sids パラメータで駅 ID の順序リストを受け取り、1 件以上解決できれば表示を開き、既存パラメータとの後方互換性を保持し、auto/theme パラメータの併用に対応しています。
Out of Scope Changes check ✅ Passed すべての変更が #6002 の要件に関連しており、新しい GET_STATIONS_BY_IDS GraphQL クエリの追加、openRouteByStationIds ヘルパー関数の実装、sids パラメータの処理ロジック、および包括的なテストケースの追加はすべて要件に沿っています。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/deep-link-multi-line-route

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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

@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

🤖 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/useDeepLink.ts`:
- Around line 320-323: The current parsing of sids in useDeepLink.ts using
Number.parseInt allows invalid tokens like "123x" to be accepted; instead
validate each token as a strict positive integer string (e.g. match /^\d+$/)
before converting, then map to Number (or parseInt) and filter > 0 to produce
stationIds; ensure you trim and skip empty tokens so only fully numeric,
positive IDs are included.
🪄 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: 817c3b76-f659-420d-841b-52cdde0df504

📥 Commits

Reviewing files that changed from the base of the PR and between 7e84d73 and b01930e.

📒 Files selected for processing (3)
  • src/hooks/useDeepLink.test.tsx
  • src/hooks/useDeepLink.ts
  • src/lib/graphql/queries.ts

Comment thread src/hooks/useDeepLink.ts Resolved
Number.parseInt は "123x" を 123 として silently 受理してしまうため、
カンマ区切り各トークンを正整数として厳密検証する。
@TinyKitten

Copy link
Copy Markdown
Member Author

Fixes Applied Successfully

Fixed 1 file based on 1 CodeRabbit feedback item.

Files modified:

  • src/hooks/useDeepLink.ts
  • src/hooks/useDeepLink.test.tsx (regression test added)

Commit: 1666d8a99548456669b72bdc7a96c4ac87080f21

The latest autofix changes are on the feature/deep-link-multi-line-route branch.

coderabbitai[bot]
coderabbitai Bot previously requested changes May 16, 2026

@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

🧹 Nitpick comments (2)
src/hooks/useDeepLink.test.tsx (2)

948-965: 💤 Low value

テストセットアップが useSetAtom 呼び出し順序に依存しています。

このカスタムアトムセットアップは setupAtoms のロジックを複製し、4 つのセッターを想定しています(line 953 のコメントで文書化済み)。Hook 内で useSetAtom の呼び出し順序や数が変更されるとテストが壊れる可能性があります。

現状のコメントによる文書化は有用ですが、以下の選択肢も検討できます:

  • setupAtoms を拡張して追加セッターをオプションで受け取る
  • テスト内で個別に atom モックを構成する

ただし、この特殊なテストケースとしては現状でも許容範囲内です。

🤖 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/useDeepLink.test.tsx` around lines 948 - 965, テストが useSetAtom
の呼び出し順序(mockUseSetAtom, setters, atomCallIdx)に依存して壊れやすいため、mockUseSetAtom
の実装を呼び出し時の引数(渡される atom)に基づいて返すセッターを決定するよう修正してください;具体的には現在の順序依存ロジック(atomCallIdx と
setters 配列)を削除し、受け取った atom を識別して stationState, navigationState, lineState,
themePreferenceAtom のそれぞれに対応するモック関数(mockSetStationState, mockSetNavigationState,
mockSetLineState, mockSetThemePreference)を返すマッピングに置き換えるか、あるいは setupAtoms
を拡張して必要なセッターを明示的に渡せるようにしてテスト内で個別構成するようにしてください。

887-926: ⚡ Quick win

部分的な結果が返された場合の状態更新の挙動が未検証です。

このテストは sids が指定されたときに sgid/lid/lgid が無視されることを検証していますが、モックは 2 つの ID に対して 1 つの駅しか返していません(line 909)。state が更新されたかどうかの検証がないため、部分的な結果の扱いが不明瞭です。

以下のいずれかを推奨します:

  1. モックを 2 駅返すように変更し、テストの焦点を「レガシーパラメータの無視」に絞る
  2. 部分的な結果に対する state の挙動(更新される/されない)を明示的に検証する

比較: line 860-885 では空結果時に mockSetStationState が呼ばれないことを検証しています。

💡 提案: テストデータを完全な結果セットに変更
 it('sidsが指定されている場合はsgid/lid/lgidを無視する', async () => {
-  const station = createStation(1131211, {
+  const stationA = createStation(1131211, {
     line: { id: 11302 },
   } as Parameters<typeof createStation>[1]);
+  const stationB = createStation(1131310, {
+    line: { id: 11302 },
+  } as Parameters<typeof createStation>[1]);

   mockGetInitialURL.mockResolvedValue(
     'CanaryTrainLCD://route?sids=1131211,1131310&sgid=99&lid=999&lgid=42&dir=0'
   );
   mockParse.mockReturnValue({
     queryParams: {
       sids: '1131211,1131310',
       sgid: '99',
       lid: '999',
       lgid: '42',
       dir: '0',
     },
   });

   setupAtoms();
   const { mockFetchByIds, mockFetchByLine, mockFetchByGroup } =
     setupQueries();
   mockFetchByIds.mockResolvedValue({
-    data: { stations: [station] },
+    data: { stations: [stationA, stationB] },
   });

   render(
     <HookBridge
       onReady={() => {
         /* noop */
       }}
     />
   );

   await waitFor(() => {
     expect(mockFetchByIds).toHaveBeenCalled();
   });

   expect(mockFetchByLine).not.toHaveBeenCalled();
   expect(mockFetchByGroup).not.toHaveBeenCalled();
 });
🤖 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/useDeepLink.test.tsx` around lines 887 - 926, The test currently
mocks mockFetchByIds to return only one station for two sids, leaving
partial-result behavior unverified; either update the mock in this test
(mockFetchByIds.mockResolvedValue) to return both stations (e.g., two
createStation(...) entries) so the test solely asserts that legacy params are
ignored (expect mockFetchByLine and mockFetchByGroup not called), OR keep the
single-station mock and add explicit assertions about state updates (e.g.,
expect mockSetStationState or the hook's state-mutator to have been called/not
called with the partial result) so partial-result handling is verified; modify
the test body around the mockFetchByIds setup and the expectations accordingly.
🤖 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/useDeepLink.ts`:
- Around line 347-352: Validate sgid and lid as strict positive integers in
useDeepLink (not just Number() + truthy). Instead of allowing
Number(sgid)/Number(lid) to pass, ensure the raw values are finite integers > 0
(e.g. test /^\d+$/ on the input strings or use Number.isInteger(parsed) &&
parsed > 0 && isFinite(parsed)) before assigning stationGroupId/lineId and
returning early; if the check fails, treat as no-op. Update the checks around
variables sgid, lid, stationGroupId, and lineId to mirror the strict validation
used for sids.

---

Nitpick comments:
In `@src/hooks/useDeepLink.test.tsx`:
- Around line 948-965: テストが useSetAtom の呼び出し順序(mockUseSetAtom, setters,
atomCallIdx)に依存して壊れやすいため、mockUseSetAtom の実装を呼び出し時の引数(渡される
atom)に基づいて返すセッターを決定するよう修正してください;具体的には現在の順序依存ロジック(atomCallIdx と setters
配列)を削除し、受け取った atom を識別して stationState, navigationState, lineState,
themePreferenceAtom のそれぞれに対応するモック関数(mockSetStationState, mockSetNavigationState,
mockSetLineState, mockSetThemePreference)を返すマッピングに置き換えるか、あるいは setupAtoms
を拡張して必要なセッターを明示的に渡せるようにしてテスト内で個別構成するようにしてください。
- Around line 887-926: The test currently mocks mockFetchByIds to return only
one station for two sids, leaving partial-result behavior unverified; either
update the mock in this test (mockFetchByIds.mockResolvedValue) to return both
stations (e.g., two createStation(...) entries) so the test solely asserts that
legacy params are ignored (expect mockFetchByLine and mockFetchByGroup not
called), OR keep the single-station mock and add explicit assertions about state
updates (e.g., expect mockSetStationState or the hook's state-mutator to have
been called/not called with the partial result) so partial-result handling is
verified; modify the test body around the mockFetchByIds setup and the
expectations accordingly.
🪄 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: a93e536d-9f90-42bb-81de-f20e918b1fb5

📥 Commits

Reviewing files that changed from the base of the PR and between 1666d8a and 178c990.

📒 Files selected for processing (2)
  • src/hooks/useDeepLink.test.tsx
  • src/hooks/useDeepLink.ts

Comment thread src/hooks/useDeepLink.ts Resolved
@TinyKitten

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

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 Request ChangesとUnsolved Threadが0件なのにRequest changeなのはなぜですか?

@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check current review state of the PR
gh pr view 6003 --repo TrainLCD/MobileApp --json reviews,reviewDecision,state | jq .

# Also list all reviews
gh api repos/TrainLCD/MobileApp/pulls/6003/reviews | jq '[.[] | {id, user: .user.login, state, submitted_at, body}]'

Length of output: 20941


@TinyKitten: 状況を確認しました。レビュー履歴を見ると、以下の流れになっています:

時刻 (UTC) コミット ステータス 内容
13:51:59 b01930e CHANGES_REQUESTED sids の parseInt バリデーション指摘
14:00:01 1666d8a ✅ APPROVED fix 適用後、承認
14:23:54 178c990 CHANGES_REQUESTED 新たな指摘(後述)

1666d8a(autofix 適用済みコミット)の後、さらに新しいコミット 178c9902 がプッシュされたため、CodeRabbit がその差分を増分レビューした結果、再度 CHANGES_REQUESTED を出しています。これが現在の「Request Changes」の原因です。

最新レビューの指摘内容は:

アクショナブル(1件)

  • src/hooks/useDeepLink.ts Line 347–352: sgid / lid を Number() + truthy チェックだけでなく、sids と同様に厳密な正の整数として検証するべき(/^\d+$/ によるチェックや Number.isInteger 等)

Nitpick(2件)

  • src/hooks/useDeepLink.test.tsx Line 948–965: useSetAtom の呼び出し順序に依存したテストセットアップの改善提案
  • src/hooks/useDeepLink.test.tsx Line 887–926: 部分的な結果が返された場合の挙動が未検証という指摘

CodeRabbit の UI 上でスレッドが見えていない場合は、最新のレビューコメントが別ページやコミット差分ビューに表示されている可能性があります。上記アクショナブルコメントへの対応(または無視の判断)をいただければ、その後承認に切り替えることができます。いかがでしょうか?

(´・ω・`)

@TinyKitten

Copy link
Copy Markdown
Member Author

@coderabbitai useDeepLink.tsはすでに全研対応していますよね

@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the current state of sgid/lid validation in useDeepLink.ts
cat src/hooks/useDeepLink.ts | grep -n "sgid\|lid\|lgid\|parseInt\|Number\|isInteger\|^\\\d" | head -60

# Also show context around the relevant lines
sed -n '330,380p' src/hooks/useDeepLink.ts

Length of output: 2025


@TinyKitten: sids 経路のバリデーションは /^\d+$/ による厳密なチェックが適用されており、こちらは完全に対応済みです ✓

ただし、レガシーの sgid/lid 経路(Lines 347–354) は現在も Number() + truthy チェックのままです:

const stationGroupId = Number(sgid);
const lineId = Number(lid);

if (!stationGroupId || !lineId) {
  return;
}

この実装だと:

  • "123x" → NaN → falsy → 弾かれる ✅
  • "123.5" → 123.5 → truthy → 素通りしてしまう ⚠️

sids と同様に正の整数バリデーションを適用するなら、以下のようにできます:

const sgidStr = sgid ?? '';
const lidStr  = lid  ?? '';
if (!/^\d+$/.test(sgidStr) || !/^\d+$/.test(lidStr)) {
  return;
}
const stationGroupId = Number(sgidStr);
const lineId         = Number(lidStr);
if (!stationGroupId || !lineId) {
  return;
}

ただし sgid/lid はレガシー経路であり、GraphQL サーバー側で Int! として型検証されるため、"123.5" が実際に問題になるケースは稀です。厳密にしたくない場合はそのままにする判断も十分あり得ます。どうされますか?

@TinyKitten

Copy link
Copy Markdown
Member Author

@coderabbitai

ただし、レガシーの sgid/lid 経路(Lines 347–354) は現在も Number() + truthy チェックのままです:

#6003 (comment)

@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Fetch the specific review comment r3252931369
gh api repos/TrainLCD/MobileApp/pulls/comments/3252931369 | jq '{id, body, path, line, diff_hunk, user: .user.login}'

Length of output: 5537


@TinyKitten: おっしゃる通りです、失礼しました!

そのスレッドは私自身が Issue #6004 として起票し、スレッドもクローズ済みでした。改めて同じ指摘を繰り返してしまっていました。

sgid/lid のバリデーション改善は #6004 でトラッキング済みなので、この PR の CHANGES_REQUESTED の残件はそれが原因ではありません。改めて確認すると、現時点でブロッカーとなるアクショナブルな未解決指摘はありません。承認に切り替えます。

(´;ω;`)

[approve]

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