// static/script.js
"use strict"; // より厳格なエラーチェック
// --- グローバル変数 ---
let learningData = null; // 学習データ - { title: '...', items: [...] } の形式を想定
let currentItemIndex = 0; // 現在表示中のアイテムインデックス
let currentMode = 'quiz'; // 現在のモード 'quiz' or 'summary'
let correctEffectTimeout; // 正解エフェクト非表示用のタイマーID
let correctEffect = null; // 正解エフェクト要素
let sideMenu = null; // サイドメニュー要素
let menuOverlay = null; // メニューオーバーレイ要素
// --- 共通関数 ---
/**
* 指定されたURLに遷移します。遷移前にメニューを閉じます。
* @param {string} url - 遷移先のURL
*/
function navigateTo(url) {
closeMenu(); // 遷移前にメニューを閉じる
setTimeout(() => {
window.location.href = url;
}, 100); // 少し遅延させて遷移
}
/**
* サイドメニューを開きます。
*/
function openMenu() {
console.log("Opening menu...");
if (sideMenu && menuOverlay) {
sideMenu.classList.add('open');
menuOverlay.classList.add('open');
document.body.classList.add('menu-open');
} else {
console.error("Side menu or overlay element not found. Cannot open menu.");
}
}
/**
* サイドメニューを閉じます。
*/
function closeMenu() {
if (sideMenu && menuOverlay) {
sideMenu.classList.remove('open');
menuOverlay.classList.remove('open');
document.body.classList.remove('menu-open');
}
}
/**
* ローディングスピナーを表示/非表示します。 learning.html の要素表示/非表示も制御します。
* @param {boolean} show - trueで表示、falseで非表示
* @param {string} buttonId - 操作対象のボタンID (input.html用)
*/
function toggleLoading(show, buttonId = 'generate-button') {
const targetButton = document.getElementById(buttonId);
// input.html の generate-button の処理
if (targetButton && buttonId === 'generate-button') {
const spinner = targetButton.querySelector('.loading-spinner');
const buttonText = targetButton.querySelector('.button-text');
if (show) {
targetButton.disabled = true;
if (spinner) spinner.style.display = 'inline-block';
if (buttonText) buttonText.textContent = '生成中...';
} else {
targetButton.disabled = false;
if (spinner) spinner.style.display = 'none';
if (buttonText) buttonText.textContent = '生成する';
}
}
// learning.html 用の汎用ローディング表示
const loadingIndicator = document.getElementById('mode-indicator');
const cardElement = document.getElementById('learning-card');
const paginationElement = document.querySelector('.pagination'); // pagination要素を取得
const optionsArea = document.getElementById('options-area');
const tapToShowElement = document.getElementById('tap-to-show');
const currentPathname = window.location.pathname;
if (currentPathname.endsWith('/learning') || currentPathname.endsWith('/learning.html')) {
if (show) {
// ローディング開始時の処理
if (loadingIndicator) {
loadingIndicator.textContent = '読み込み中...';
loadingIndicator.classList.add('loading');
}
if (cardElement) cardElement.style.opacity = '0.5';
if (paginationElement) paginationElement.style.display = 'none'; // ★ 非表示にする
if (optionsArea) optionsArea.style.display = 'none';
if (tapToShowElement) tapToShowElement.style.display = 'none';
} else {
// ローディング終了時の処理
if (loadingIndicator) {
loadingIndicator.classList.remove('loading');
// モード表示は displayCurrentItem で更新される
}
if (cardElement) cardElement.style.opacity = '1';
// ★★★ ローディング終了時にページネーションを再表示 ★★★
if (paginationElement) paginationElement.style.display = 'flex'; // CSSでのdisplay値 (通常flex) に戻す
// optionsArea と tapToShowElement の表示は displayCurrentItem で適切に制御される
}
}
}
/**
* エラーメッセージを表示します。
* @param {string} message - 表示するエラーメッセージ
* @param {string} elementId - メッセージを表示する要素のID (デフォルト: 'error-message')
*/
function displayErrorMessage(message, elementId = 'error-message') {
const errorElement = document.getElementById(elementId);
if (errorElement) {
errorElement.textContent = message;
errorElement.style.display = message ? 'block' : 'none';
} else {
if (message) {
console.error(`Error element with ID "${elementId}" not found. Cannot display message: ${message}`);
}
}
}
// --- 画面遷移用関数 ---
function goToInput() {
navigateTo('/input');
}
function goToHistory() {
navigateTo('/history');
}
function goToSettings() {
navigateTo('/settings');
}
function goToLearning(contentId) {
if (contentId) {
navigateTo(`/learning?id=${encodeURIComponent(contentId)}`);
} else {
console.error('goToLearning requires a content ID.');
alert('学習コンテンツのIDが見つかりません。');
}
}
// --- input.html 用の処理 ---
/**
* 生成フォームの送信処理
*/
async function handleGenerateSubmit() {
const urlInput = document.getElementById('youtube-url');
const youtubeUrl = urlInput.value.trim();
const errorMsgElementId = 'error-message';
displayErrorMessage('', errorMsgElementId);
if (!youtubeUrl) {
displayErrorMessage('YouTubeリンクを入力してください。', errorMsgElementId);
return false;
}
try {
const urlObj = new URL(youtubeUrl);
const validHostnames = ['www.youtube.com', 'youtube.com', 'youtu.be'];
if (!validHostnames.includes(urlObj.hostname)) throw new Error('Invalid hostname');
if (urlObj.hostname === 'youtu.be' && urlObj.pathname.length <= 1) throw new Error('Missing video ID for youtu.be');
if (urlObj.hostname.includes('youtube.com')) {
if (urlObj.pathname === '/watch' && !urlObj.searchParams.has('v')) throw new Error('Missing video ID parameter (v=...) for youtube.com/watch');
if (urlObj.pathname.startsWith('/shorts/') && urlObj.pathname.length <= 8) throw new Error('Missing video ID for youtube.com/shorts/');
}
} catch (e) {
console.warn("Invalid URL format:", e.message);
displayErrorMessage('有効なYouTube動画のリンクを入力してください。(例: https://www.youtube.com/watch?v=...)', errorMsgElementId);
return false;
}
toggleLoading(true, 'generate-button');
try {
const response = await fetch('/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify({ url: youtubeUrl }),
});
let result;
try {
result = await response.json();
} catch (jsonError) {
console.error('Failed to parse JSON response:', jsonError);
throw new Error(response.ok ? 'サーバーからの応答形式が不正です。' : `サーバーエラー (${response.status})`);
}
// サーバーが返すJSON構造 { success: true, data: { id: '...' } } を期待
if (response.ok && result && typeof result === 'object' && result.success && result.data && result.data.id) {
console.log("Generation successful, navigating to learning page with ID:", result.data.id);
goToLearning(result.data.id);
} else {
console.error('Generation API call failed or returned unexpected structure:', result);
const serverMessage = (result && typeof result === 'object' && result.message) ||
(result && typeof result === 'object' && result.error && result.error.message) ||
(response.ok ? '生成に失敗しました (不明な応答形式)。' : `サーバーエラー (${response.status})`);
displayErrorMessage(serverMessage, errorMsgElementId);
}
} catch (error) {
console.error('Error during generation request:', error);
const userMessage = error.message.includes('Failed to fetch') ? 'サーバーに接続できませんでした。' : `エラー: ${error.message}`;
displayErrorMessage(userMessage, errorMsgElementId);
} finally {
toggleLoading(false, 'generate-button');
}
return false;
}
// --- learning.html 用の処理 ---
/**
* learning.html の初期化: コンテンツデータを取得し、最初のアイテムを表示
*/
async function initializeLearningScreen() {
console.log('Initializing Learning Screen...');
const params = new URLSearchParams(window.location.search);
const contentId = params.get('id');
if (!contentId) {
displayLearningError('学習コンテンツのIDが見つかりません。');
return;
}
console.log('Content ID:', contentId);
toggleLoading(true); // ★ ローディング開始 (ここでpaginationが消える)
try {
const response = await fetch(`/api/learning/${contentId}`);
if (!response.ok) {
let errorMessage = `サーバーからのデータ取得に失敗 (${response.status})`;
try {
const errorData = await response.json();
errorMessage = errorData.message || errorMessage;
} catch (e) { console.warn('Failed to parse error response as JSON.'); }
throw new Error(errorMessage);
}
// サーバーからの応答がオブジェクト {success: ..., data: {...}} であると想定
const result = await response.json();
console.log('Fetched data object:', result);
// 応答の形式をチェック
if (!result || typeof result !== 'object' || !result.success || !result.data || !Array.isArray(result.data.items)) {
console.error('Invalid data structure received from server:', result);
throw new Error('サーバーから受け取ったデータの形式が正しくありません。');
}
// learningData を構築 (title と items を data から取得)
learningData = {
title: result.data.title || `学習セット (${contentId})`, // data.title があればそれを使う
items: result.data.items // data.items を使う
};
// アイテム配列が空でないかチェック
if (learningData.items.length === 0) {
throw new Error('学習データが見つかりませんでした (アイテムが0件)。');
}
// タイトルを設定
const titleElement = document.getElementById('learning-title');
if (titleElement) {
titleElement.textContent = learningData.title;
} else {
console.warn("Title element ('learning-title') not found.");
}
// 最初のアイテムを表示
currentItemIndex = 0;
displayCurrentItem();
} catch (error) {
console.error('Error initializing learning screen:', error);
const message = (error instanceof SyntaxError) ? `サーバー応答の解析エラー: ${error.message}` : `読み込みエラー: ${error.message}`;
displayLearningError(message); // エラー表示関数内で toggleLoading(false) が呼ばれる
} finally {
// ★ 成功時も失敗時もここでローディングを終了させる
// displayLearningError内で呼ばれる場合もあるが、成功時はここで確実に呼ぶ
toggleLoading(false); // ★ ローディング終了 (ここでpaginationが再表示される)
}
}
/**
* 現在の学習アイテムをカードに表示 (クイズ or 要約)
*/
function displayCurrentItem() {
hideCorrectEffect();
clearTimeout(correctEffectTimeout);
const cardElement = document.getElementById('learning-card');
const cardTextElement = document.getElementById('card-text');
const answerTextElement = document.getElementById('answer-text');
const tapToShowElement = document.getElementById('tap-to-show');
const optionsArea = document.getElementById('options-area');
const modeIndicator = document.getElementById('mode-indicator');
if (!cardElement || !cardTextElement || !answerTextElement || !tapToShowElement || !optionsArea || !modeIndicator) {
console.error("One or more required learning elements are missing.");
displayLearningError("画面表示に必要な要素が見つかりません。"); // エラー表示内でtoggleLoading(false)される
return;
}
if (!learningData || !learningData.items || currentItemIndex < 0 || currentItemIndex >= learningData.items.length) {
console.error('Invalid learning data or index:', learningData, currentItemIndex);
displayLearningError('表示する学習データが見つかりません。'); // エラー表示内でtoggleLoading(false)される
return;
}
const item = learningData.items[currentItemIndex];
// リセット
cardTextElement.innerHTML = '';
answerTextElement.style.display = 'none';
answerTextElement.textContent = '';
tapToShowElement.style.display = 'none';
optionsArea.innerHTML = '';
optionsArea.style.display = 'none';
modeIndicator.classList.remove('loading');
// サーバーレスポンスのキーに合わせて item.text を使用
if (item.type === 'question' && item.text && item.answer) {
currentMode = 'quiz';
modeIndicator.textContent = 'クイズモード';
cardTextElement.textContent = item.text; // 問題文
answerTextElement.textContent = `答え: ${item.answer}`;
if (item.options && Array.isArray(item.options) && item.options.length > 0) {
optionsArea.style.display = 'block'; // ★ 表示
item.options.forEach(option => {
const button = document.createElement('button');
button.classList.add('option-button');
button.textContent = option;
button.onclick = () => handleOptionClick(option);
optionsArea.appendChild(button);
});
tapToShowElement.style.display = 'block'; // ★ 表示
} else {
console.warn(`Quiz item ${currentItemIndex} has no options.`);
tapToShowElement.style.display = 'block'; // ★ 選択肢なくても解答表示は可能
}
cardElement.onclick = () => revealAnswer();
tapToShowElement.onclick = () => revealAnswer();
} else if (item.type === 'summary' && item.text) {
currentMode = 'summary';
modeIndicator.textContent = '要約モード';
cardTextElement.innerHTML = item.text.replace(/\n/g, '
');
cardElement.onclick = null;
tapToShowElement.style.display = 'none'; // ★ 非表示
optionsArea.style.display = 'none'; // ★ 非表示
} else {
console.warn('Unknown or invalid item type/data:', item);
currentMode = 'unknown';
modeIndicator.textContent = 'データエラー';
cardTextElement.textContent = `[不正なデータ形式] ${item.text || 'この項目を表示できません。'}`;
cardElement.onclick = null;
tapToShowElement.style.display = 'none'; // ★ 非表示
optionsArea.style.display = 'none'; // ★ 非表示
}
updatePagination(); // ★ ページネーションの表示/非表示ではなく、内容とボタン状態を更新
}
/**
* クイズの選択肢がクリックされたときの処理
* @param {string} selectedOption - ユーザーが選択した選択肢のテキスト
*/
function handleOptionClick(selectedOption) {
if (currentMode !== 'quiz' || !learningData || !learningData.items || !learningData.items[currentItemIndex]) return;
const answerTextElement = document.getElementById('answer-text');
if (answerTextElement && answerTextElement.style.display === 'block') return; // 解答表示済み
const currentItem = learningData.items[currentItemIndex];
const correctAnswer = currentItem.answer;
const isCorrect = selectedOption === correctAnswer;
if (isCorrect) {
console.log("Correct!");
showCorrectEffect();
} else {
console.log("Incorrect...");
}
revealAnswer(selectedOption);
}
/**
* クイズの解答を表示し、選択肢ボタンの状態を更新する
* @param {string|null} [selectedOption=null] - ユーザーが選択した選択肢。nullの場合はカードタップ等による表示。
*/
function revealAnswer(selectedOption = null) {
if (currentMode !== 'quiz' || !learningData || !learningData.items || !learningData.items[currentItemIndex]) return;
const answerTextElement = document.getElementById('answer-text');
const tapToShowElement = document.getElementById('tap-to-show');
const optionsArea = document.getElementById('options-area');
const cardElement = document.getElementById('learning-card');
if (answerTextElement && answerTextElement.style.display === 'block') return; // 表示済み
if (answerTextElement) answerTextElement.style.display = 'block'; // ★ 表示
if (tapToShowElement) tapToShowElement.style.display = 'none'; // ★ 非表示
if (cardElement) cardElement.onclick = null;
if (optionsArea) {
const correctAnswer = learningData.items[currentItemIndex].answer;
const buttons = optionsArea.querySelectorAll('.option-button');
buttons.forEach(button => {
button.disabled = true;
button.onclick = null;
const buttonText = button.textContent;
if (buttonText === correctAnswer) button.classList.add('correct');
else if (buttonText === selectedOption) button.classList.add('incorrect');
else button.classList.add('other-disabled');
});
}
}
/**
* 次の学習アイテムへ移動
*/
function goToNext() {
if (learningData && learningData.items && currentItemIndex < learningData.items.length - 1) {
currentItemIndex++;
displayCurrentItem(); // displayCurrentItem内で要素の表示/非表示が制御される
} else {
console.log("Already at the last item or no data.");
if (learningData && learningData.items && currentItemIndex === learningData.items.length - 1) {
alert("学習セットが完了しました!");
}
}
}
/**
* 前の学習アイテムへ移動
*/
function goToPrev() {
if (learningData && learningData.items && currentItemIndex > 0) {
currentItemIndex--;
displayCurrentItem(); // displayCurrentItem内で要素の表示/非表示が制御される
} else {
console.log("Already at the first item or no data.");
}
}
/**
* ページネーション(ページ番号とボタンの状態)を更新
*/
function updatePagination() {
const pageInfo = document.getElementById('page-info');
const prevButton = document.getElementById('prev-button');
const nextButton = document.getElementById('next-button');
if (!pageInfo || !prevButton || !nextButton) {
console.warn("Pagination elements not found.");
return;
}
// ★ ページネーション要素自体の表示/非表示は toggleLoading で行う
// ここでは内容とボタンの状態のみ更新
if (learningData && learningData.items && learningData.items.length > 0) {
const totalItems = learningData.items.length;
pageInfo.textContent = `${currentItemIndex + 1} / ${totalItems}`;
prevButton.disabled = currentItemIndex === 0;
nextButton.disabled = currentItemIndex === totalItems - 1;
} else {
pageInfo.textContent = '0 / 0';
prevButton.disabled = true;
nextButton.disabled = true;
}
}
/**
* learning.html でエラーが発生した場合の表示処理
* @param {string} message - 表示するエラーメッセージ
*/
function displayLearningError(message) {
const cardElement = document.getElementById('learning-card');
const titleElement = document.getElementById('learning-title');
const paginationElement = document.querySelector('.pagination');
const optionsArea = document.getElementById('options-area');
const modeIndicator = document.getElementById('mode-indicator');
const tapToShow = document.getElementById('tap-to-show');
if (titleElement) titleElement.textContent = 'エラー';
if (modeIndicator) modeIndicator.textContent = 'エラー発生';
if (cardElement) {
cardElement.innerHTML = `
${message}
`; // CSSでスタイル調整用クラス追加 cardElement.onclick = null; } // エラー時はページネーション等も非表示にする if (paginationElement) paginationElement.style.display = 'none'; if (optionsArea) { optionsArea.innerHTML = ''; optionsArea.style.display = 'none'; } if (tapToShow) tapToShow.style.display = 'none'; // ★ エラー表示関数内でも toggleLoading(false) を呼ぶことを確認(重複しても問題ない) toggleLoading(false); } /** * 正解時に「〇」エフェクトを表示する */ function showCorrectEffect() { if (correctEffect) { clearTimeout(correctEffectTimeout); correctEffect.classList.add('show'); correctEffectTimeout = setTimeout(() => { hideCorrectEffect(); }, 1000); } else { console.warn("Correct effect element not found."); } } /** * 正解エフェクトを非表示にする */ function hideCorrectEffect() { if (correctEffect && correctEffect.classList.contains('show')) { correctEffect.classList.remove('show'); } clearTimeout(correctEffectTimeout); } // --- settings.html 用の処理 --- /** * トグルスイッチの状態が変更されたときの処理 * @param {HTMLInputElement} checkbox - 変更されたチェックボックス要素 * @param {string} type - トグルの種類 ('dark', 'notification' など) */ function handleToggleChange(checkbox, type) { const isChecked = checkbox.checked; console.log(`Toggle changed for ${type}: ${isChecked}`); if (type === 'dark') { document.body.classList.toggle('dark-mode', isChecked); try { localStorage.setItem('darkModeEnabled', isChecked); } catch (e) { console.warn('Could not save dark mode preference:', e); } } else if (type === 'notification') { console.log("Notification setting toggled:", isChecked); alert(`通知設定未実装 (設定: ${isChecked ? 'ON' : 'OFF'})`); } } /** * ログアウトボタンがクリックされたときの処理 */ function handleLogout() { console.log("Logout button clicked"); // TODO: 実際のログアウト処理 alert("ログアウトしました。(開発中)"); goToInput(); } /** * ローカルストレージからダークモード設定を読み込み、bodyに適用する */ function applyDarkModePreference() { try { const darkModeEnabled = localStorage.getItem('darkModeEnabled') === 'true'; document.body.classList.toggle('dark-mode', darkModeEnabled); // console.log(`Applied dark mode preference: ${darkModeEnabled}`); } catch (e) { console.warn('Could not load/apply dark mode preference:', e); } } // --- ページの初期化処理 --- const pathname = window.location.pathname; applyDarkModePreference(); // 最初に適用 document.addEventListener('DOMContentLoaded', () => { console.log('DOM fully loaded. Path:', pathname); sideMenu = document.getElementById('side-menu'); menuOverlay = document.getElementById('menu-overlay'); if (!sideMenu || !menuOverlay) console.warn("Menu elements not found."); // learningページ固有の初期化 if (pathname.endsWith('/learning') || pathname.endsWith('/learning.html')) { correctEffect = document.getElementById('correct-effect'); if (!correctEffect) console.warn("Correct effect element not found."); initializeLearningScreen(); // ★ initializeLearningScreen を呼ぶ } // inputページ固有の初期化 if (pathname === '/' || pathname.endsWith('/input') || pathname.endsWith('/input.html')) { console.log("Initializing Input page..."); const form = document.getElementById('generate-form'); if (form) form.addEventListener('submit', (e) => { e.preventDefault(); handleGenerateSubmit(); }); else console.warn("Generate form not found."); const urlParams = new URLSearchParams(window.location.search); const initialUrl = urlParams.get('url'); if (initialUrl) { const urlInput = document.getElementById('youtube-url'); if (urlInput) urlInput.value = initialUrl; } } // historyページ固有の初期化 else if (pathname.endsWith('/history') || pathname.endsWith('/history.html')) { console.log("Initializing History page..."); // loadHistoryData(); } // settingsページ固有の初期化 else if (pathname.endsWith('/settings') || pathname.endsWith('/settings.html')) { console.log("Initializing Settings page..."); try { // ダークモードトグル状態設定 const darkModeEnabled = localStorage.getItem('darkModeEnabled') === 'true'; const toggle = document.querySelector('input[type="checkbox"][onchange*="dark"]'); if (toggle) toggle.checked = darkModeEnabled; else console.warn("Dark mode toggle not found."); } catch (e) { console.warn('Could not set dark mode toggle state:', e); } } updateFooterNavActiveState(pathname); // フッターアクティブ状態更新 closeMenu(); // 念のためメニューを閉じる }); /** * 現在のパスに基づいてフッターナビゲーションのアクティブ状態を更新 */ function updateFooterNavActiveState(currentPath) { const footerNav = document.querySelector('.footer-nav'); if (!footerNav) return; const buttons = footerNav.querySelectorAll('button'); buttons.forEach(button => { button.classList.remove('active'); const onclickAttr = button.getAttribute('onclick'); if (onclickAttr) { if ((currentPath === '/' || currentPath.endsWith('/input') || currentPath.endsWith('/input.html')) && onclickAttr.includes('goToInput')) button.classList.add('active'); else if ((currentPath.endsWith('/history') || currentPath.endsWith('/history.html')) && onclickAttr.includes('goToHistory')) button.classList.add('active'); else if ((currentPath.endsWith('/settings') || currentPath.endsWith('/settings.html')) && onclickAttr.includes('goToSettings')) button.classList.add('active'); } }); } // --- デバッグ用グローバル公開 --- // --- END OF FILE script.js ---