Skip to content

Commit

Permalink
Support Translator-api (#57)
Browse files Browse the repository at this point in the history
* feat: Translator-api

* chore: language option

* chore: remove select

* fix: lint
  • Loading branch information
yossydev authored Nov 17, 2024
1 parent ab3e165 commit d088ed1
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
74 changes: 74 additions & 0 deletions app/islands/TranslatorButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { type FC, useState } from "hono/jsx";

type SupportedTranslatorAPI =
| "en"
| "zn"
| "ja"
| "pt"
| "ru"
| "es"
| "tr"
| "hi"
| "vi"
| "bn";

const SELECT_OPTIONS: SupportedTranslatorAPI[] = [
"ja",
"en",
"zn",
"pt",
"ru",
"es",
"tr",
"hi",
"vi",
"bn",
];

type Props = {
content: string;
};

const TranslatorButton: FC<Props> = ({ content }) => {
const [value, setValue] = useState<SupportedTranslatorAPI>("ja");

// biome-ignore lint: lint/suspicious/noExplicitAny
const handleSelectChange = async (e: any) => {
setValue(e.target.value);
if (
"translation" in self &&
// biome-ignore lint: lint/suspicious/noExplicitAny
"createTranslator" in (self.translation as any)
) {
// biome-ignore lint: lint/suspicious/noExplicitAny
const translator = await (self.translation as any).createTranslator({
sourceLanguage: value,
targetLanguage: e.target.value,
});
await translator.translate(content);
} else {
window.alert("The Translator API is not supported");
}
};

return (
<>
<label for="pet-select">translate to: </label>
<select
onChange={handleSelectChange}
value={value}
class="cursor-pointer"
>
{SELECT_OPTIONS.map((value) => {
return (
<option key={value} value={value}>
{value}
</option>
);
})}
</select>
</>
);
};

export default TranslatorButton;
4 changes: 4 additions & 0 deletions app/routes/posts/_renderer.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { jsxRenderer } from "hono/jsx-renderer";
import LikeButton from "../../islands/LikeButton";
import SnsButton from "../../islands/SnsButton";
import TranslatorButton from "../../islands/TranslatorButton";

export default jsxRenderer(({ children, Layout, frontmatter }) => {
const _title = `${frontmatter?.title} | yossy.dev`;
return (
<Layout title={_title} description={frontmatter?.description}>
<div class="text-right mt-3">
<TranslatorButton content={children?.toString() as string} />
</div>
<div class="markdown">
<h1>{frontmatter?.title}</h1>
<dl class="flex items-center gap-3">
Expand Down

0 comments on commit d088ed1

Please sign in to comment.