Skip to content

Conversation

@psm1st
Copy link
Member

@psm1st psm1st commented Apr 16, 2025

🧐 체크리스트

  • 코드 실행 확인: yarn build 또는 npm run build 실행 후 정상적으로 동작하는지 확인했나요?
  • 테스트 통과 여부: Jest 테스트를 실행했고 모든 테스트가 통과했나요? (yarn test)
  • ESLint & Prettier 검사: yarn lintyarn prettify 실행 후 문제가 없나요?
  • PR 제목 확인: PR 제목이 feat:, fix:, chore: 등 커밋 컨벤션을 따르고 있나요?
  • 변경 사항 설명: PR 설명에 변경된 내용을 충분히 작성했나요?
  • 리뷰어가 이해하기 쉽게 작성: 코드 리뷰어가 쉽게 이해할 수 있도록 가독성 높은 코드를 작성했나요?
  • 문서 업데이트 필요 여부: 기능 추가/변경 사항이 있다면 README.md 또는 관련 문서를 업데이트했나요?

Summary by CodeRabbit

  • New Features

    • Introduced a simplified popup interface with a single "읽어줘!" button that retrieves and reads aloud the current page's text in Korean.
  • Bug Fixes

    • Improved error handling to alert users if text retrieval fails.
  • Style

    • Updated popup styling using Tailwind CSS for a cleaner, more minimal look.

@coderabbitai
Copy link

coderabbitai bot commented Apr 16, 2025

Walkthrough

The changes introduce a complete rewrite of the popup component for a Chrome extension. The previous multi-component structure with scrolling features was replaced by a single, minimal React functional component. This new component directly interacts with the Chrome extension API to retrieve visible page text from the active tab and uses the Web Speech API to read it aloud in Korean. The UI is now a single button labeled "읽어줘!", and error handling was added. The entry point was updated to render this new default component, and styling is handled with Tailwind CSS.

Changes

File(s) Change Summary
src/popup/component.tsx Replaced previous multi-component popup with a new minimal React functional component using hooks. Removed scrolling, injected scripts, and imported components. Now queries active tab, retrieves text, uses Web Speech API for speech synthesis, and updates UI to a single button. Added error handling and Tailwind CSS styling.
src/popup/index.tsx Updated import to use the new default export (Component) and renders it. Removed obsolete code comments.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Popup (Component)
    participant Chrome Extension API
    participant Active Tab
    participant Web Speech API

    User->>Popup (Component): Clicks "읽어줘!" button
    Popup (Component)->>Chrome Extension API: Query active tab
    Chrome Extension API->>Active Tab: Send message to get page text
    Active Tab-->>Chrome Extension API: Respond with page text
    Chrome Extension API-->>Popup (Component): Return page text
    Popup (Component)->>Web Speech API: Speak text in Korean
Loading

Poem

🐇
A button to click, a voice to be heard,
With code now simpler—no scrolling deferred.
"읽어줘!" it sings, in Korean it reads,
Chrome's APIs answer the popup's new needs.
Tailwind brings style, the old ways are gone—
Just press and listen, the rabbit hops on!
🗣️✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (5)
src/popup/component.tsx (3)

4-4: Consider using a more descriptive component name

The generic name "Component" doesn't convey the purpose of this component. A more descriptive name would improve code readability.

-const Component = () => {
+const TextToSpeechPopup = () => {

Don't forget to update the export and import in index.tsx as well.


18-23: Consider adding voice options and speech configuration

The current implementation uses default settings for speech synthesis. Consider adding options for voice selection, speed, and pitch to improve user experience.

const utterance = new SpeechSynthesisUtterance(
    response.text,
);
utterance.lang = "ko-KR";
+utterance.rate = 1.0; // Speech rate (0.1 to 10)
+utterance.pitch = 1.0; // Speech pitch (0 to 2)
+
+// Optional: Select a specific voice if available
+const voices = speechSynthesis.getVoices();
+const koreanVoice = voices.find(voice => voice.lang === 'ko-KR');
+if (koreanVoice) {
+    utterance.voice = koreanVoice;
+}
speechSynthesis.speak(utterance);

34-35: Replace test title with a production-ready title

The current title "VOIM tts test" suggests this is a test component. If this is intended for production, consider updating the title.

<h1 className="text-xl font-semibold mb-2 text-gray-800">
-    VOIM tts test
+    VOIM 텍스트 읽기
</h1>
src/popup/index.tsx (2)

3-4: Consider using the imported browser polyfill consistently

The file imports the webextension-polyfill as browser, but the component uses the direct chrome API. Consider using the polyfill consistently across your codebase for better cross-browser compatibility.

Either:

  1. Use the polyfill in your Component implementation:
// In component.tsx
-chrome.tabs.query
+browser.tabs.query
  1. Or remove the unused polyfill if you're targeting Chrome only:
-import browser from "webextension-polyfill";

4-4: Update import to match suggested component name

If you rename the component as suggested in the previous file review, update the import here as well.

-import Component from "./component";
+import TextToSpeechPopup from "./component";

And update the render call accordingly:

-root.render(<Component />);
+root.render(<TextToSpeechPopup />);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5e6c486 and 301405d.

⛔ Files ignored due to path filters (2)
  • dist/manifest.json is excluded by !**/dist/**
  • dist/popup.html is excluded by !**/dist/**
📒 Files selected for processing (2)
  • src/popup/component.tsx (1 hunks)
  • src/popup/index.tsx (2 hunks)
🔇 Additional comments (1)
src/popup/index.tsx (1)

22-22: Ensure the component implementation aligns with the PR objectives

According to the PR objectives, this PR is focused on completing tests. However, the changes appear to be a complete reimplementation of the component. Ensure that proper testing has been included as mentioned in the PR objectives.

Have you included Jest tests for this component as mentioned in the PR checklist? The PR description mentions running yarn test to ensure all tests pass.

Comment on lines +11 to 28
chrome.tabs.sendMessage(
tabs[0].id,
{ type: "GET_PAGE_TEXT" },
(response) => {
if (response?.text) {
setPageText(response.text);

const utterance = new SpeechSynthesisUtterance(
response.text,
);
utterance.lang = "ko-KR";
speechSynthesis.speak(utterance);
} else {
alert("페이지의 텍스트를 가져오지 못했어요.");
}
},
);
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for chrome.runtime.lastError

When using callback-based Chrome API methods, you should check for chrome.runtime.lastError to handle potential errors from the messaging system.

chrome.tabs.sendMessage(
    tabs[0].id,
    { type: "GET_PAGE_TEXT" },
    (response) => {
+       if (chrome.runtime.lastError) {
+           alert(`오류: ${chrome.runtime.lastError.message}`);
+           return;
+       }
        if (response?.text) {
            setPageText(response.text);

            const utterance = new SpeechSynthesisUtterance(
                response.text,
            );
            utterance.lang = "ko-KR";
            speechSynthesis.speak(utterance);
        } else {
            alert("페이지의 텍스트를 가져오지 못했어요.");
        }
    },
);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
chrome.tabs.sendMessage(
tabs[0].id,
{ type: "GET_PAGE_TEXT" },
(response) => {
if (response?.text) {
setPageText(response.text);
const utterance = new SpeechSynthesisUtterance(
response.text,
);
utterance.lang = "ko-KR";
speechSynthesis.speak(utterance);
} else {
alert("페이지의 텍스트를 가져오지 못했어요.");
}
},
);
});
chrome.tabs.sendMessage(
tabs[0].id,
{ type: "GET_PAGE_TEXT" },
(response) => {
if (chrome.runtime.lastError) {
alert(`오류: ${chrome.runtime.lastError.message}`);
return;
}
if (response?.text) {
setPageText(response.text);
const utterance = new SpeechSynthesisUtterance(
response.text,
);
utterance.lang = "ko-KR";
speechSynthesis.speak(utterance);
} else {
alert("페이지의 텍스트를 가져오지 못했어요.");
}
},
);

Comment on lines +1 to +46
import React, { useState } from "react";
import "../css/app.css";

const Component = () => {
const [pageText, setPageText] = useState("");

const getTextAndSpeak = () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (!tabs[0]?.id) return;

chrome.tabs.sendMessage(
tabs[0].id,
{ type: "GET_PAGE_TEXT" },
(response) => {
if (response?.text) {
setPageText(response.text);

const utterance = new SpeechSynthesisUtterance(
response.text,
);
utterance.lang = "ko-KR";
speechSynthesis.speak(utterance);
} else {
alert("페이지의 텍스트를 가져오지 못했어요.");
}
},
);
});
}

// // // //
};

export function Popup() {
// Sends the `popupMounted` event
React.useEffect(() => {
browser.runtime.sendMessage({ popupMounted: true });
}, []);

// Renders the component tree
return (
<div>
<div className="mx-4 my-4 bg-black">
<Hello />
<hr />
<Scroller
onClickScrollTop={() => {
executeScript(scrollToTopPosition);
}}
onClickScrollBottom={() => {
executeScript(scrollToBottomPosition);
}}
/>
</div>
<div className="w-64 p-4 bg-white rounded-lg shadow-lg">
<h1 className="text-xl font-semibold mb-2 text-gray-800">
VOIM tts test
</h1>
<button
onClick={getTextAndSpeak}
className="w-full mt-2 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded text-sm"
>
읽어줘!
</button>
</div>
);
}
};

export default Component;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Functional implementation, but lacks user experience considerations

The implementation is functional but has a few issues that should be addressed:

  1. No cleanup mechanism for speech synthesis when the popup closes
  2. No way to stop reading once started
  3. Limited error handling
  4. Hardcoded Korean language without user options
  5. No loading/in-progress indicators

Consider enhancing the user experience with these improvements:

import React, { useState, useEffect } from "react";
import "../css/app.css";

const Component = () => {
    const [pageText, setPageText] = useState("");
+   const [isLoading, setIsLoading] = useState(false);
+   const [isSpeaking, setIsSpeaking] = useState(false);

+   useEffect(() => {
+       return () => {
+           // Cleanup speech synthesis when component unmounts
+           speechSynthesis.cancel();
+       };
+   }, []);

    const getTextAndSpeak = () => {
+       setIsLoading(true);
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            if (!tabs[0]?.id) return;

            chrome.tabs.sendMessage(
                tabs[0].id,
                { type: "GET_PAGE_TEXT" },
                (response) => {
+                   setIsLoading(false);
                    if (response?.text) {
                        setPageText(response.text);

                        const utterance = new SpeechSynthesisUtterance(
                            response.text,
                        );
                        utterance.lang = "ko-KR";
+                       setIsSpeaking(true);
+                       utterance.onend = () => setIsSpeaking(false);
+                       utterance.onerror = () => {
+                           setIsSpeaking(false);
+                           alert("읽기 중 오류가 발생했습니다.");
+                       };
                        speechSynthesis.speak(utterance);
                    } else {
                        alert("페이지의 텍스트를 가져오지 못했어요.");
                    }
                },
            );
        });
    };

+   const stopSpeaking = () => {
+       speechSynthesis.cancel();
+       setIsSpeaking(false);
+   };

    return (
        <div className="w-64 p-4 bg-white rounded-lg shadow-lg">
            <h1 className="text-xl font-semibold mb-2 text-gray-800">
                VOIM tts test
            </h1>
            <button
                onClick={getTextAndSpeak}
+               disabled={isLoading || isSpeaking}
                className="w-full mt-2 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded text-sm"
            >
-               읽어줘!
+               {isLoading ? "로딩 중..." : isSpeaking ? "읽는 중..." : "읽어줘!"}
            </button>
+           {isSpeaking && (
+               <button
+                   onClick={stopSpeaking}
+                   className="w-full mt-2 py-2 bg-red-500 hover:bg-red-600 text-white rounded text-sm"
+               >
+                   중지
+               </button>
+           )}
        </div>
    );
};

export default Component;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import React, { useState } from "react";
import "../css/app.css";
const Component = () => {
const [pageText, setPageText] = useState("");
const getTextAndSpeak = () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (!tabs[0]?.id) return;
chrome.tabs.sendMessage(
tabs[0].id,
{ type: "GET_PAGE_TEXT" },
(response) => {
if (response?.text) {
setPageText(response.text);
const utterance = new SpeechSynthesisUtterance(
response.text,
);
utterance.lang = "ko-KR";
speechSynthesis.speak(utterance);
} else {
alert("페이지의 텍스트를 가져오지 못했어요.");
}
},
);
});
}
// // // //
};
export function Popup() {
// Sends the `popupMounted` event
React.useEffect(() => {
browser.runtime.sendMessage({ popupMounted: true });
}, []);
// Renders the component tree
return (
<div>
<div className="mx-4 my-4 bg-black">
<Hello />
<hr />
<Scroller
onClickScrollTop={() => {
executeScript(scrollToTopPosition);
}}
onClickScrollBottom={() => {
executeScript(scrollToBottomPosition);
}}
/>
</div>
<div className="w-64 p-4 bg-white rounded-lg shadow-lg">
<h1 className="text-xl font-semibold mb-2 text-gray-800">
VOIM tts test
</h1>
<button
onClick={getTextAndSpeak}
className="w-full mt-2 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded text-sm"
>
읽어줘!
</button>
</div>
);
}
};
export default Component;
import React, { useState, useEffect } from "react";
import "../css/app.css";
const Component = () => {
const [pageText, setPageText] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [isSpeaking, setIsSpeaking] = useState(false);
useEffect(() => {
return () => {
// Cleanup speech synthesis when component unmounts
speechSynthesis.cancel();
};
}, []);
const getTextAndSpeak = () => {
setIsLoading(true);
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (!tabs[0]?.id) return;
chrome.tabs.sendMessage(
tabs[0].id,
{ type: "GET_PAGE_TEXT" },
(response) => {
setIsLoading(false);
if (response?.text) {
setPageText(response.text);
const utterance = new SpeechSynthesisUtterance(
response.text,
);
utterance.lang = "ko-KR";
setIsSpeaking(true);
utterance.onend = () => setIsSpeaking(false);
utterance.onerror = () => {
setIsSpeaking(false);
alert("읽기 중 오류가 발생했습니다.");
};
speechSynthesis.speak(utterance);
} else {
alert("페이지의 텍스트를 가져오지 못했어요.");
}
},
);
});
};
const stopSpeaking = () => {
speechSynthesis.cancel();
setIsSpeaking(false);
};
return (
<div className="w-64 p-4 bg-white rounded-lg shadow-lg">
<h1 className="text-xl font-semibold mb-2 text-gray-800">
VOIM tts test
</h1>
<button
onClick={getTextAndSpeak}
disabled={isLoading || isSpeaking}
className="w-full mt-2 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded text-sm"
>
{isLoading ? "로딩 중..." : isSpeaking ? "읽는 중..." : "읽어줘!"}
</button>
{isSpeaking && (
<button
onClick={stopSpeaking}
className="w-full mt-2 py-2 bg-red-500 hover:bg-red-600 text-white rounded text-sm"
>
중지
</button>
)}
</div>
);
};
export default Component;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants