Skip to content

useTTSText のアナウンステンプレートをミニエンジン化してリファクタリング - #5916

Merged
TinyKitten merged 2 commits into
devfrom
feature/tts-template-engine
May 10, 2026
Merged

TinyKitten merged 2 commits into
devfrom
feature/tts-template-engine

Conversation

@TinyKitten

@TinyKitten TinyKitten commented May 10, 2026 •

Copy link
Copy Markdown
Member

概要

useTTSText の巨大化していたテンプレートリテラル群を、極小テンプレートエンジン + テーマ別宣言的テンプレート + リスト整形ヘルパに分離。挙動は byte-for-byte で維持し、既存のスナップショットテスト 31 件すべて pass。

変更の種類

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

変更内容

  • src/hooks/tts/templateEngine.ts: {var} と {#if/:else/} のみサポートする ~80 行のミニエンジンを新規追加 (反復は意図的に未サポート、配列は呼び出し側で文字列化して渡す)
  • src/hooks/tts/templates.ts: テーマ別の NEXT/ARRIVING テンプレートを宣言的に定義 (JA/EN それぞれ)
  • src/hooks/tts/formatters.ts: formatLinesListJa / formatLinesListEn / formatJrWestStopsList* 等のリスト整形ヘルパを新規追加
  • src/hooks/tts/templateEngine.test.ts: エンジン単体の挙動テスト 20 件を追加
  • src/hooks/useTTSText.ts: 1381 → 465 行 (約 -66%) に縮小。巨大な japaneseTemplate / englishTemplate useMemo を廃止し「context 構築 → テーマ解決 → render」の3ステップに再構成

テスト

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

既存の src/hooks/useTTSText.test.tsx 31 件 + 新規 templateEngine.test.ts 20 件、合計 51 件すべて pass を確認。

関連Issue

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

Summary by CodeRabbit

  • New Features

    • TTS用のテンプレートベース出力を導入し、テーマ別に日本語/英語の音声文を柔軟に生成。
    • 日本語の読み仮名挿入や英語の自然な列挙・端末表現など、発話向けフォーマットを追加。
  • Refactor

    • TTS生成ロジックを整理し、再利用可能なテンプレートコンテキストで出力を安定化。
  • Tests

    • テンプレートエンジンの網羅的な単体テストを追加。

Review Change Stack

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

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2c00243b-f039-44c2-866a-749ff1843381

📥 Commits

Reviewing files that changed from the base of the PR and between a99f1d1 and ca76fa4.

📒 Files selected for processing (2)
  • src/hooks/tts/templateEngine.test.ts
  • src/hooks/tts/templateEngine.ts

📝 Walkthrough

Walkthrough

テンプレートエンジンとテンプレート定義、言語別フォーマッターを追加し、useTTSText を TemplateContext を使うテンプレートベースの出力に差し替えています。

変更内容

TTS テンプレートエンジン統合

Layer / File(s) Summary
テンプレートエンジン実装
src/hooks/tts/templateEngine.ts
AST ベースのパーサーで {name} 変数補間と {#if ...}{:else}{/if} 条件ブロックをサポート。truthiness 判定と構文エラー検出を行い、compile() はレンダラーを返す。
テンプレートエンジンテスト
src/hooks/tts/templateEngine.test.ts
変数補間、複数変数、数値、null/undefined/false の扱い、ネストした if/else、空白保持、SSML タグのそのまま通過、構文エラーケースを追加テスト。
フォーマッター関数
src/hooks/tts/formatters.ts
replaceJapaneseText による日本語 SSML <sub> 包含(カタカナ→ひらがな変換とフォールバック)、路線・駅リストの日本語/英語整形、JR_WEST 停車駅リスト(最大5件)と最初の接続路線英語フレーズを追加。
テーマ別テンプレート定義
src/hooks/tts/templates.ts
テーマ別の NEXT / ARRIVING テンプレートレンダラー群(日本語・英語)を JA_TEMPLATES / EN_TEMPLATES として定義。t() ヘルパでテンプレートをコンパイル。
useTTSText フック統合
src/hooks/useTTSText.ts
TemplateContext を useMemo で構築し、フォーマッターで作った断片とフラグをテンプレートエンジンに渡して ja/en の主文と NEXT 文を生成。古いインラインマップと定数を削除しメモ化を整理。

Sequence Diagram

sequenceDiagram
  participant Hook as useTTSText
  participant Formatters as formatters.ts
  participant Engine as templateEngine.compile
  participant Templates as JA/EN_TEMPLATES
  participant Output as TTSTextResult
  Hook->>Formatters: フラグと断片を生成(replaceJapaneseText等)
  Hook->>Engine: TemplateContext を渡してレンダラー実行
  Engine->>Templates: テンプレート内で変数参照と if 評価
  Templates->>Engine: レンダリング結果(jaText/enText/nextText)を返す
  Engine->>Output: 最終 TTS テキストを提供
Loading

推定コード確認労力

🎯 4 (Complex) | ⏱️ ~45 分

詩

🐰 新しいテンプレート通り、
ひらがなで歌うカタカナ、
路線と駅が整えられ、
フックは静かにコンテキストを渡し、
TTS は滑らかに告げる。

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed タイトルはPRの主要な変更内容(useTTSText のテンプレートをミニエンジン化してのリファクタリング)を正確に反映しており、簡潔で明確です。
Description check ✅ Passed 説明は必須セクション(概要、変更の種類、変更内容、テスト、関連Issue)をすべて充実した内容で記載しており、テンプレートの要件を満たしています。
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.

✏️ 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/tts-template-engine

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: 4

🤖 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/tts/formatters.ts`:
- Around line 92-95: formatFirstConnectedLineEnPhrase currently early-returns
when first.nameTtsSegments is missing, which drops lines that only have
nameRoman; change the guard to base the decision on the rendered text: call
wrapPhoneme(first.nameTtsSegments, first.nameRoman) into a local (e.g.
renderedName) and return '' only if renderedName is falsy, otherwise return `on
the ${renderedName}`; reference symbols: formatFirstConnectedLineEnPhrase,
lines, first.nameTtsSegments, first.nameRoman, wrapPhoneme.
- Around line 5-17: The function replaceJapaneseText currently hardcodes the
fallback '<sub alias="かくえきていしゃ">各駅停車</sub>', causing unrelated outputs for
station/line/company names; change replaceJapaneseText to not embed a fixed
fallback: accept an explicit fallback parameter (string | undefined) or return
an empty string when both name and nameKatakana are missing, keep the
katakanaToHiragana behavior for the alias branch, and then update callers that
need "各駅停車" (e.g., trainTypeJa / trainTypeJaPlain / trainTypeJaKyushu) to pass
that specific fallback explicitly.

In `@src/hooks/tts/templateEngine.ts`:
- Around line 71-77: The current {:else} handling silently overwrites a previous
alternate by assigning ifNode.alternate = [] even when an alternate already
exists; change the logic in the {:else} branch (the block that reads tag ===
'{:else}' and references top.ifNode, ifNode.alternate, and stack) to first check
whether ifNode.alternate is already set and, if so, throw a syntax Error (e.g.,
"{:else} already defined for this {`#if`}") instead of replacing it; otherwise,
initialize ifNode.alternate = [] and push the new stack frame as before.

In `@src/hooks/useTTSText.ts`:
- Around line 285-316: The context builder in the useMemo (function useTTSText)
must not construct a context when nextStation is unresolved; update the
early-exit condition to return null if nextStation is falsy (in addition to
currentLine and selectedBound) so no downstream fields (e.g., nextStationJa
which calls replaceJapaneseText) are evaluated with undefined values; locate the
useMemo that returns the TemplateContext and add a guard like `if (!currentLine
|| !selectedBound || !nextStation) return null`, or otherwise ensure nextStation
is checked before calling replaceJapaneseText and initializing nextStationJa.
🪄 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: 3c560c32-fa92-4b94-a835-1097e63e3961

📥 Commits

Reviewing files that changed from the base of the PR and between 1a39f04 and a99f1d1.

📒 Files selected for processing (5)
  • src/hooks/tts/formatters.ts
  • src/hooks/tts/templateEngine.test.ts
  • src/hooks/tts/templateEngine.ts
  • src/hooks/tts/templates.ts
  • src/hooks/useTTSText.ts

Comment thread src/hooks/tts/formatters.ts Resolved
Comment thread src/hooks/tts/formatters.ts Resolved
Comment thread src/hooks/tts/templateEngine.ts Resolved
Comment thread src/hooks/useTTSText.ts Resolved
@TinyKitten

Copy link
Copy Markdown
Member Author

CodeRabbit Autofix Summary

CodeRabbit から指摘された 4 件をレビューし、1 件を本 PR で適用、残り 3 件は別チケットに切り出しました。

Applied (1 件)

  • src/hooks/tts/templateEngine.ts: 重複した {:else} を黙って先行の alternate で上書きする挙動を、Duplicate {:else} in {#if} block の構文エラーとして検出するよう修正。templateEngine.test.ts に対応するテスト 1 件を追加 (合計 52 tests pass)。

Commit: ca76fa4

Deferred (3 件) → Issue #5917

以下 3 件は本 PR のリファクタ前から存在する既存挙動で、純粋リファクタとして byte-for-byte 維持するため別 issue (#5917) にまとめました:

  • src/hooks/tts/formatters.ts:17 — replaceJapaneseText の 各駅停車 フォールバック (汎用ヘルパが train type 専用 fallback を持つ問題)
  • src/hooks/tts/formatters.ts:95 — formatFirstConnectedLineEnPhrase が nameTtsSegments の有無のみで判定 (nameRoman のみあるケースで脱落)
  • src/hooks/useTTSText.ts:316 — nextStation 未解決時の context 構築で誤案内になりうる

@TinyKitten
TinyKitten merged commit e4dafbd into dev May 10, 2026
5 checks passed
@TinyKitten
TinyKitten deleted the feature/tts-template-engine branch May 10, 2026 23:09
This was referenced May 11, 2026
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