Commit ·
0842d68
0
Parent(s):
Initial commit: TranslateGemma browser translator with Transformers.js
Browse files- Complete translation UI with 56 languages
- Mobile-responsive design
- Private & offline-capable translation
- URL hash sharing functionality
- Auto-translate with debounce
- Copy and share features
- Google Translate-inspired design
Files changed (38)
- .agents/skills/tailwind-v4/SKILL.mdAdded+225
- .agents/skills/tailwind-v4/references/dark-mode.mdAdded+458
- .agents/skills/tailwind-v4/references/setup.mdAdded+264
- .agents/skills/tailwind-v4/references/theming.mdAdded+492
- .gitignoreAdded+24
- .prettierignoreAdded+7
- .prettierrcAdded+7
- README.mdAdded+37
- eslint.config.jsAdded+28
- index.htmlAdded+51
- package-lock.jsonAdded
- package.jsonAdded+37
- public/favicon.svgAdded
- public/gemma.svgAdded
- public/hf-logo.svgAdded
- src/App.tsxAdded+103
- src/Initialize.tsxAdded+104
- src/Translate.tsxAdded+280
- src/ai/Translator.tsAdded+64
- src/components/LanguageSelector.tsxAdded+116
- src/constants.tsAdded+72
- src/index.cssAdded+66
- src/main.tsxAdded+10
- src/theme/button/Button.tsxAdded+78
- src/theme/form/Textarea.tsxAdded+60
- src/theme/index.tsAdded+3
- src/theme/misc/Loader.tsxAdded+15
- src/types/transformers.tsAdded+77
- src/utils/classnames.tsAdded+13
- src/utils/countWords.tsAdded+13
- src/utils/format.tsAdded+28
- src/vite-env.d.tsAdded+1
- tsconfig.app.jsonAdded+26
- tsconfig.app.tsbuildinfoAdded+1
- tsconfig.jsonAdded+7
- tsconfig.node.jsonAdded+23
- tsconfig.node.tsbuildinfoAdded+1
- vite.config.tsAdded+8
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225---name: tailwind-v4description: Tailwind CSS v4 with CSS-first configuration and design tokens. Use when setting up Tailwind v4, defining theme variables, using OKLCH colors, or configuring dark mode. Triggers on @theme, @tailwindcss/vite, oklch, CSS variables, --color-, tailwind v4.---
# Tailwind CSS v4 Best Practices
## Quick Reference
**Vite Plugin Setup**:```ts// vite.config.tsimport tailwindcss from '@tailwindcss/vite';import { defineConfig } from 'vite';
export default defineConfig({ plugins: [tailwindcss()],});```
**CSS Entry Point**:```css/* src/index.css */@import 'tailwindcss';```
**@theme Inline Directive**:```css@theme inline { --color-primary: oklch(60% 0.24 262); --color-surface: oklch(98% 0.002 247);}```
## Key Differences from v3
| Feature | v3 | v4 ||---------|----|----|| Configuration | tailwind.config.js | @theme in CSS || Build Tool | PostCSS plugin | @tailwindcss/vite || Colors | rgb() / hsl() | oklch() (default) || Theme Extension | extend: {} in JS | CSS variables || Dark Mode | darkMode config option | CSS variants |
## @theme Directive Modes
### default (standard mode)Generates CSS variables that can be referenced elsewhere:```css@theme { --color-brand: oklch(60% 0.24 262);}
/* Generates: :root { --color-brand: oklch(...); } *//* Usage: text-brand → color: var(--color-brand) */```
**Note**: You can also use `@theme default` explicitly to mark theme values that can be overridden by non-default @theme declarations.
### inlineInlines values directly without CSS variables (better performance):```css@theme inline { --color-brand: oklch(60% 0.24 262);}
/* Usage: text-brand → color: oklch(60% 0.24 262) */```
### referenceInlines values as fallbacks without emitting CSS variables:```css@theme reference { --color-internal: oklch(50% 0.1 180);}
/* No :root variable, but utilities use fallback *//* Usage: bg-internal → background-color: var(--color-internal, oklch(50% 0.1 180)) */```
## OKLCH Color Format
OKLCH provides perceptually uniform colors with better consistency across hues:
```cssoklch(L% C H)```
- **L (Lightness)**: 0% (black) to 100% (white)- **C (Chroma)**: 0 (gray) to ~0.4 (vibrant)- **H (Hue)**: 0-360 degrees (red → yellow → green → blue → magenta)
**Examples**:```css--color-sky-500: oklch(68.5% 0.169 237.323); /* Bright blue */--color-red-600: oklch(57.7% 0.245 27.325); /* Vibrant red */--color-zinc-900: oklch(21% 0.006 285.885); /* Near-black gray */```
## CSS Variable Naming
Tailwind v4 uses double-dash CSS variable naming conventions:
```css@theme { /* Colors: --color-{name}-{shade} */ --color-primary-500: oklch(60% 0.24 262);
/* Spacing: --spacing multiplier */ --spacing: 0.25rem; /* Base unit for spacing scale */
/* Fonts: --font-{family} */ --font-display: 'Inter Variable', system-ui, sans-serif;
/* Breakpoints: --breakpoint-{size} */ --breakpoint-lg: 64rem;
/* Custom animations: --animate-{name} */ --animate-fade-in: fade-in 0.3s ease-out;}```
## No Config Files Needed
Tailwind v4 eliminates configuration files:
- **No `tailwind.config.js`** - Use @theme in CSS instead- **No `postcss.config.js`** - Use @tailwindcss/vite plugin- **TypeScript support** - Add `@types/node` for path resolution
```json{ "devDependencies": { "@tailwindcss/vite": "^4.0.0", "@types/node": "^22.0.0", "tailwindcss": "^4.0.0", "vite": "^6.0.0" }}```
## Progressive Disclosure
- **Setup & Installation**: See [references/setup.md](references/setup.md) for Vite plugin configuration, package setup, TypeScript config- **Theming & Design Tokens**: See [references/theming.md](references/theming.md) for @theme modes, color palettes, custom fonts, animations- **Dark Mode Strategies**: See [references/dark-mode.md](references/dark-mode.md) for media queries, class-based, attribute-based approaches
## Decision Guide
### When to use @theme inline vs default
**Use `@theme inline`**:- Better performance (no CSS variable overhead)- Static color values that won't change- Animation keyframes with multiple values- Utilities that need direct value inlining
**Use `@theme` (default)**:- Dynamic theming with JavaScript- CSS variable references in custom CSS- Values that change based on context- Better debugging (inspect CSS variables in DevTools)
### When to use @theme reference
**Use `@theme reference`**:- Provide fallback values without CSS variable overhead- Values that should work even if variable isn't defined- Reducing :root bloat while maintaining utility support- Combining with inline for direct value substitution
## Common Patterns
### Two-Tier Variable System
Semantic variables that map to design tokens:
```css@theme { /* Design tokens (OKLCH colors) */ --color-blue-600: oklch(54.6% 0.245 262.881); --color-slate-800: oklch(27.9% 0.041 260.031);
/* Semantic mappings */ --color-primary: var(--color-blue-600); --color-surface: var(--color-slate-800);}
/* Usage: bg-primary, bg-surface */```
### Custom Font Configuration
```css@theme { --font-display: 'Inter Variable', system-ui, sans-serif; --font-mono: 'JetBrains Mono', ui-monospace, monospace;
--font-display--font-variation-settings: 'wght' 400; --font-display--font-feature-settings: 'cv02', 'cv03', 'cv04';}
/* Usage: font-display, font-mono */```
### Animation Keyframes
```css@theme inline { --animate-beacon: beacon 2s ease-in-out infinite;
@keyframes beacon { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(1.05); } }}
/* Usage: animate-beacon */```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458# Dark Mode Strategies
## Contents
- [Media Query Strategy](#media-query-strategy)- [Class-Based Strategy](#class-based-strategy)- [Attribute-Based Strategy](#attribute-based-strategy)- [Theme Switching Implementation](#theme-switching-implementation)- [Respecting User Preferences](#respecting-user-preferences)
---
## Media Query Strategy
Use the system preference for dark mode detection.
### Configuration
**Default behavior** (v4):```css/* No configuration needed - dark: variant works by default */@import 'tailwindcss';```
**Generated CSS**:```css@media (prefers-color-scheme: dark) { .dark\:bg-slate-900 { background-color: oklch(20.8% 0.042 265.755); }}```
### Usage
```tsxexport function Card({ children }: { children: React.ReactNode }) { return ( <div className="bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-50"> {children} </div> );}```
### Pros & Cons
**Pros**:- Respects system preference automatically- No JavaScript needed- Simple implementation- No FOUC (flash of unstyled content)
**Cons**:- Users can't override system preference- No manual toggle control- Changes when system setting changes
### When to Use
- Documentation sites- Content-focused websites- Apps where system preference is preferred- No need for manual theme switching
## Class-Based Strategy
Toggle dark mode with a `.dark` class on the root element.
### Configuration
**Pure v4 approach**: Use a v3 config file with darkMode setting:
```js// tailwind.config.js (for v3 compatibility)module.exports = { darkMode: 'class', // or 'selector' (same as 'class')};```
**Note**: In pure v4, the default `dark:` variant uses media queries (`prefers-color-scheme: dark`). To use class-based dark mode, you need to either:1. Use a v3 config file with `darkMode: 'class'` (shown above)2. Use `@import "tailwindcss/compat"` and provide a config3. Define a custom variant with `@custom-variant`
### Generated CSS
```css.dark .dark\:bg-slate-900 { background-color: oklch(20.8% 0.042 265.755);}```
### Usage
```tsxexport function App() { const [isDark, setIsDark] = useState(false);
useEffect(() => { if (isDark) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } }, [isDark]);
return ( <div className="bg-white dark:bg-slate-900"> <button onClick={() => setIsDark(!isDark)}> Toggle Theme </button> </div> );}```
### Pros & Cons
**Pros**:- Full JavaScript control- User can override system preference- Easy to implement manual toggle- Widely supported pattern
**Cons**:- Requires JavaScript- Potential FOUC without SSR handling- Class management overhead
### When to Use
- Applications with theme toggle- User preference override needed- Dashboard/admin interfaces- Apps with per-user theme settings
## Attribute-Based Strategy
Use a `data-theme` attribute for more semantic theming.
### Configuration (v3 compat)
```js// tailwind.config.js (v3 compat mode)module.exports = { darkMode: ['class', '[data-theme="dark"]'],};```
### Generated CSS
```css[data-theme="dark"] .dark\:bg-slate-900 { background-color: oklch(20.8% 0.042 265.755);}```
### Usage
```tsxexport function App() { const [theme, setTheme] = useState<'light' | 'dark'>('light');
useEffect(() => { document.documentElement.setAttribute('data-theme', theme); }, [theme]);
return ( <div className="bg-white dark:bg-slate-900"> <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}> Toggle Theme </button> </div> );}```
### Multiple Themes
Extend beyond light/dark with multiple theme attributes:
```tsxtype Theme = 'light' | 'dark' | 'aviation' | 'high-contrast';
export function App() { const [theme, setTheme] = useState<Theme>('light');
useEffect(() => { document.documentElement.setAttribute('data-theme', theme); }, [theme]);
return ( <div className="bg-white dark:bg-slate-900 [&[data-theme='aviation']]:bg-blue-950"> <select value={theme} onChange={(e) => setTheme(e.target.value as Theme)}> <option value="light">Light</option> <option value="dark">Dark</option> <option value="aviation">Aviation</option> <option value="high-contrast">High Contrast</option> </select> </div> );}```
### Pros & Cons
**Pros**:- Semantic HTML attribute- Supports multiple themes (not just light/dark)- Easy to inspect in DevTools- Clear intent
**Cons**:- Requires JavaScript- More verbose selector in CSS- Less common pattern
### When to Use
- Multi-theme applications- Semantic HTML preferences- Complex theming systems- Better DevTools debugging
## Theme Switching Implementation
Complete implementation with persistence and SSR support.
### React Hook
```tsx// hooks/use-theme.tsimport { useEffect, useState } from 'react';
type Theme = 'light' | 'dark' | 'system';
export function useTheme() { const [theme, setTheme] = useState<Theme>(() => { if (typeof window === 'undefined') return 'system'; return (localStorage.getItem('theme') as Theme) || 'system'; });
useEffect(() => { const root = document.documentElement; const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
const effectiveTheme = theme === 'system' ? systemTheme : theme;
root.classList.remove('light', 'dark'); root.classList.add(effectiveTheme);
localStorage.setItem('theme', theme); }, [theme]);
// Listen for system theme changes useEffect(() => { if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); const handleChange = () => { const systemTheme = mediaQuery.matches ? 'dark' : 'light'; document.documentElement.classList.remove('light', 'dark'); document.documentElement.classList.add(systemTheme); };
mediaQuery.addEventListener('change', handleChange); return () => mediaQuery.removeEventListener('change', handleChange); }, [theme]);
return { theme, setTheme };}```
### Theme Provider Component
```tsx// components/theme-provider.tsximport { createContext, useContext, type ReactNode } from 'react';import { useTheme } from '@/hooks/use-theme';
type ThemeContextValue = ReturnType<typeof useTheme>;
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
export function ThemeProvider({ children }: { children: ReactNode }) { const value = useTheme();
return ( <ThemeContext.Provider value={value}> {children} </ThemeContext.Provider> );}
export function useThemeContext() { const context = useContext(ThemeContext); if (!context) { throw new Error('useThemeContext must be used within ThemeProvider'); } return context;}```
### Theme Toggle Component
```tsx// components/theme-toggle.tsximport { Moon, Sun, Monitor } from 'lucide-react';import { useThemeContext } from '@/components/theme-provider';import { Button } from '@/components/ui/button';
export function ThemeToggle() { const { theme, setTheme } = useThemeContext();
const cycleTheme = () => { const themes: Array<'light' | 'dark' | 'system'> = ['light', 'dark', 'system']; const currentIndex = themes.indexOf(theme); const nextIndex = (currentIndex + 1) % themes.length; setTheme(themes[nextIndex]); };
const Icon = theme === 'light' ? Sun : theme === 'dark' ? Moon : Monitor;
return ( <Button variant="outline" size="icon" onClick={cycleTheme} aria-label={`Current theme: ${theme}. Click to cycle themes.`} > <Icon className="h-4 w-4" /> </Button> );}```
### SSR Script (Prevent FOUC)
Inject this script before any styled content to prevent flash:
```tsx// app/layout.tsx (Next.js example)export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en" suppressHydrationWarning> <head> <script dangerouslySetInnerHTML={{ __html: ` (function() { const theme = localStorage.getItem('theme') || 'system'; const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; const effectiveTheme = theme === 'system' ? systemTheme : theme; document.documentElement.classList.add(effectiveTheme); })(); `, }} /> </head> <body> <ThemeProvider> {children} </ThemeProvider> </body> </html> );}```
## Respecting User Preferences
### Reduced Motion
Always respect `prefers-reduced-motion`:
```css@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; }}```
**Usage in components**:```tsxexport function Card() { return ( <div className="transition-all duration-300 motion-reduce:transition-none"> Content </div> );}```
### High Contrast
Support high contrast mode:
```css@media (prefers-contrast: high) { .button { border-width: 2px; }}```
**Tailwind utilities**:```html<button class="border contrast-more:border-2"> High Contrast Button</button>```
### Forced Colors
Respect forced colors mode (Windows High Contrast):
```tsxexport function Card() { return ( <div className="bg-white dark:bg-slate-900 forced-colors:bg-[Canvas] forced-colors:border forced-colors:border-[CanvasText]"> Content </div> );}```
### Combined Example
```tsxexport function AccessibleCard({ children }: { children: React.ReactNode }) { return ( <div className={` bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-50 rounded-lg transition-colors duration-200 motion-reduce:transition-none border border-transparent contrast-more:border-slate-300 forced-colors:bg-[Canvas] forced-colors:border-[CanvasText] `} > {children} </div> );}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264# Setup & Installation
## Contents
- [Package Installation](#package-installation)- [Vite Plugin Configuration](#vite-plugin-configuration)- [TypeScript Configuration](#typescript-configuration)- [CSS Entry Point](#css-entry-point)- [Why No Config Files](#why-no-config-files)
---
## Package Installation
Install Tailwind CSS v4 with the Vite plugin:
```bashpnpm add -D tailwindcss@next @tailwindcss/vite@next```
**Complete package.json example**:```json{ "name": "amelia-dashboard", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "dependencies": { "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@tailwindcss/vite": "^4.0.0", "@types/node": "^22.0.0", "@vitejs/plugin-react": "^5.0.0", "tailwindcss": "^4.0.0", "typescript": "^5.6.0", "vite": "^6.0.0" }}```
## Vite Plugin Configuration
Use the `@tailwindcss/vite` plugin (NOT the PostCSS plugin):
```ts// vite.config.tsimport tailwindcss from '@tailwindcss/vite';import react from '@vitejs/plugin-react';import { defineConfig } from 'vite';
export default defineConfig({ plugins: [ react(), tailwindcss(), ],});```
**Plugin options**:```tsexport type PluginOptions = { /** * Optimize and minify the output CSS. * Default: true in build mode, false in dev mode */ optimize?: boolean | { minify?: boolean };};
// Example with optionstailwindcss({ optimize: { minify: true, },});```
**How it works**:- Scans source files for Tailwind class candidates- Intercepts CSS files containing `@import 'tailwindcss'`- Generates utilities based on detected classes- Watches for file changes in dev mode- Optimizes and minifies in build mode
## TypeScript Configuration
Add `@types/node` for path resolution in Vite config:
```json{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true,
/* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "isolatedModules": true, "moduleDetection": "force", "noEmit": true, "jsx": "react-jsx",
/* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true,
/* Path resolution */ "types": ["node"], "baseUrl": ".", "paths": { "@/*": ["./src/*"] } }, "include": ["src"]}```
**Why `@types/node` is needed**:- Vite uses Node.js path resolution APIs- Required for `import.meta.env` types- Enables `path.resolve()` in config files
## CSS Entry Point
Create a single CSS file that imports Tailwind:
```css/* src/index.css */@import 'tailwindcss';```
**That's it.** No other imports or configuration needed.
**Import in your app**:```tsx// src/main.tsximport './index.css';import React from 'react';import ReactDOM from 'react-dom/client';import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictMode> <App /> </React.StrictMode>);```
**Advanced: Multiple entry points**:```css/* src/index.css */@import 'tailwindcss';
/* Custom theme for this entry point */@theme { --color-primary: oklch(60% 0.24 262);}
/* Custom utilities */@layer utilities { .content-auto { content-visibility: auto; }}```
## Why No Config Files
Tailwind v4 eliminates separate configuration files in favor of CSS-first configuration.
### No `tailwind.config.js`
**v3 approach** (separate JS config):```js// tailwind.config.jsmodule.exports = { theme: { extend: { colors: { primary: '#3b82f6', }, }, },};```
**v4 approach** (CSS-first):```css@theme { --color-primary: oklch(60% 0.24 262);}```
**Benefits**:- Configuration lives with styles- No build-time JS evaluation- Better CSS tooling support (syntax highlighting, autocomplete)- Easier to understand what CSS gets generated- No context switching between files
### No `postcss.config.js`
**v3 approach** (PostCSS plugin):```js// postcss.config.jsmodule.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, },};```
**v4 approach** (Vite plugin):```ts// vite.config.tsimport tailwindcss from '@tailwindcss/vite';
export default defineConfig({ plugins: [tailwindcss()],});```
**Benefits**:- Faster builds (no PostCSS overhead)- Integrated with Vite's dev server- Better HMR (Hot Module Replacement)- Automatic source map generation- Native ES modules support
### Content Detection
**v3 approach** (manual content paths):```js// tailwind.config.jsmodule.exports = { content: ['./src/**/*.{js,ts,jsx,tsx}'],};```
**v4 approach** (automatic scanning):```css/* Auto-scans all files by default */@import 'tailwindcss';
/* Optional: Custom source patterns */@source "src/**/*.{js,ts,jsx,tsx}";@source "components/**/*.vue";```
**Benefits**:- Zero configuration by default- Explicit control when needed- CSS-based configuration- Easier to understand and debug123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492# Theming & Design Tokens
## Contents
- [@theme Directive Modes](#theme-directive-modes)- [CSS Variable Naming Conventions](#css-variable-naming-conventions)- [OKLCH Color System](#oklch-color-system)- [Aviation Theme Example](#aviation-theme-example)- [Two-Tier Variable System](#two-tier-variable-system)- [Custom Font Configuration](#custom-font-configuration)- [Animation Keyframes](#animation-keyframes)
---
## @theme Directive Modes
Tailwind v4 provides multiple modes for defining theme values. Modes can be combined (e.g., `@theme default inline`, `@theme inline reference`).
### @theme (default mode)
Generates CSS variables that can be referenced in custom CSS:
```css@theme { --color-brand: oklch(60% 0.24 262); --spacing: 0.25rem;}```
**Generated CSS**:```css:root { --color-brand: oklch(60% 0.24 262); --spacing: 0.25rem;}```
**Usage in utilities**:```html<div class="text-brand">Uses var(--color-brand)</div>```
**Usage in custom CSS**:```css.custom-element { color: var(--color-brand); padding: calc(var(--spacing) * 4);}```
### @theme inline
Inlines values directly without CSS variable indirection:
```css@theme inline { --color-brand: oklch(60% 0.24 262);}```
**Generated CSS** (when `text-brand` is used):```css.text-brand { color: oklch(60% 0.24 262);}```
**When to use**:- Better performance (no `var()` lookups)- Static values that won't change- Utilities with multiple values (animations, shadows)- Production builds with no runtime theming
### @theme reference
Inlines values as fallbacks without emitting CSS variables to :root:
```css@theme reference { --color-internal: oklch(50% 0.1 180);}```
**Generated CSS** (when `bg-internal` is used):```css.bg-internal { background-color: var(--color-internal, oklch(50% 0.1 180));}```
**Key behavior**: No `:root` variable is created, but the utility still works by using the value as a fallback in `var()`.
**When to use**:- Provide fallback values without CSS variable overhead- Reduce :root bloat while maintaining utility functionality- Values that should work even if the variable isn't defined elsewhere- Combine with `inline` for direct value substitution (e.g., `@theme reference inline`)
### @theme default
Explicitly marks theme values as defaults that can be overridden:
```css@theme default { --color-primary: oklch(60% 0.24 262);}
/* Later in the file or another file */@theme { --color-primary: oklch(70% 0.20 180); /* This overrides the default */}```
**Generated CSS**:```css:root, :host { --color-primary: oklch(70% 0.20 180);}```
**When to use**:- Providing base theme values that can be customized- Library or framework default themes- Creating overridable design systems- Used extensively in Tailwind's built-in `theme.css`
**Mode combinations**:- `@theme default inline` - Default values, inlined directly- `@theme default reference` - Default fallbacks without :root emission- `@theme default inline reference` - All three combined
## CSS Variable Naming Conventions
Tailwind v4 uses consistent naming patterns for theme variables:
### Colors
```css--color-{name}-{shade}```
**Examples**:```css@theme { --color-primary-500: oklch(60% 0.24 262); --color-surface-900: oklch(21% 0.006 286); --color-success-600: oklch(62.7% 0.194 149);}
/* Usage: text-primary-500, bg-surface-900, border-success-600 */```
### Spacing
```css--spacing: {base-unit}```
**Example**:```css@theme { --spacing: 0.25rem; /* Base unit (4px at 16px root) */}
/* Generated scale: p-1 → padding: calc(0.25rem * 1) → 4px p-4 → padding: calc(0.25rem * 4) → 16px p-12 → padding: calc(0.25rem * 12) → 48px*/```
### Fonts
```css--font-{family}--font-{family}--{feature}```
**Examples**:```css@theme { --font-sans: ui-sans-serif, system-ui, sans-serif; --font-mono: 'JetBrains Mono', monospace; --font-display: 'Inter Variable', system-ui;
--font-display--font-variation-settings: 'wght' 400; --font-display--font-feature-settings: 'cv02', 'cv03';}
/* Usage: font-sans, font-mono, font-display */```
### Breakpoints
```css--breakpoint-{size}: {value}```
**Examples**:```css@theme { --breakpoint-sm: 40rem; /* 640px */ --breakpoint-md: 48rem; /* 768px */ --breakpoint-lg: 64rem; /* 1024px */ --breakpoint-xl: 80rem; /* 1280px */ --breakpoint-2xl: 96rem; /* 1536px */}```
### Animations
```css--animate-{name}: {animation-value}```
**Examples**:```css@theme inline { --animate-spin: spin 1s linear infinite; --animate-pulse: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; --animate-beacon: beacon 2s ease-in-out infinite;
@keyframes spin { to { transform: rotate(360deg); } }
@keyframes pulse { 50% { opacity: 0.5; } }
@keyframes beacon { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(1.05); } }}
/* Usage: animate-spin, animate-pulse, animate-beacon */```
## OKLCH Color System
OKLCH (Oklab LCH) provides perceptually uniform colors with consistent lightness across all hues.
### Syntax
```cssoklch(L% C H / A)```
- **L (Lightness)**: 0% (black) to 100% (white)- **C (Chroma)**: 0 (gray) to ~0.4 (vibrant)- **H (Hue)**: 0-360 degrees- **A (Alpha)**: Optional, 0-1
### Hue Wheel
``` 0° / 360° - Red 30° - Orange 60° - Yellow 120° - Green 180° - Cyan 240° - Blue 270° - Indigo 300° - Magenta```
### Complete Color Palette
```css@theme { /* Blue scale (H ≈ 260) */ --color-blue-50: oklch(97% 0.014 254.604); --color-blue-100: oklch(93.2% 0.032 255.585); --color-blue-200: oklch(88.2% 0.059 254.128); --color-blue-300: oklch(80.9% 0.105 251.813); --color-blue-400: oklch(70.7% 0.165 254.624); --color-blue-500: oklch(62.3% 0.214 259.815); --color-blue-600: oklch(54.6% 0.245 262.881); --color-blue-700: oklch(48.8% 0.243 264.376); --color-blue-800: oklch(42.4% 0.199 265.638); --color-blue-900: oklch(37.9% 0.146 265.522); --color-blue-950: oklch(28.2% 0.091 267.935);
/* Slate scale (neutral with slight blue tint) */ --color-slate-50: oklch(98.4% 0.003 247.858); --color-slate-100: oklch(96.8% 0.007 247.896); --color-slate-200: oklch(92.9% 0.013 255.508); --color-slate-300: oklch(86.9% 0.022 252.894); --color-slate-400: oklch(70.4% 0.04 256.788); --color-slate-500: oklch(55.4% 0.046 257.417); --color-slate-600: oklch(44.6% 0.043 257.281); --color-slate-700: oklch(37.2% 0.044 257.287); --color-slate-800: oklch(27.9% 0.041 260.031); --color-slate-900: oklch(20.8% 0.042 265.755); --color-slate-950: oklch(12.9% 0.042 264.695);}```
### Chroma Guidelines
- **0**: Pure gray (achromatic)- **0.01-0.05**: Subtle tint (slate, zinc)- **0.10-0.15**: Muted colors (good for backgrounds)- **0.15-0.25**: Vibrant colors (good for UI elements)- **0.25-0.40**: Maximum saturation (use sparingly)
## Aviation Theme Example
Custom color palette for an aviation-themed dashboard:
```css@theme { /* Flight status colors */ --color-on-time: oklch(72.3% 0.219 149.579); /* Green-600 */ --color-delayed: oklch(76.9% 0.188 70.08); /* Amber-500 */ --color-cancelled: oklch(63.7% 0.237 25.331); /* Red-500 */ --color-diverted: oklch(68.5% 0.169 237.323); /* Sky-500 */
/* Navigation colors */ --color-runway: oklch(87.1% 0.006 286.286); /* Zinc-300 */ --color-taxiway: oklch(70.5% 0.015 286.067); /* Zinc-400 */ --color-apron: oklch(55.2% 0.016 285.938); /* Zinc-500 */
/* Radar colors */ --color-primary-radar: oklch(74.6% 0.16 232.661); /* Sky-400 */ --color-secondary-radar: oklch(76.5% 0.177 163.223); /* Emerald-400 */
/* Map layers */ --color-airspace-class-a: oklch(70.7% 0.165 254.624); /* Blue-400 */ --color-airspace-class-b: oklch(84.1% 0.238 128.85); /* Lime-400 */ --color-airspace-class-c: oklch(71.8% 0.202 349.761); /* Pink-400 */}```
## Two-Tier Variable System
Separate design tokens from semantic naming:
```css@theme { /* Tier 1: Design tokens (OKLCH primitives) */ --color-blue-600: oklch(54.6% 0.245 262.881); --color-slate-50: oklch(98.4% 0.003 247.858); --color-slate-800: oklch(27.9% 0.041 260.031); --color-slate-900: oklch(20.8% 0.042 265.755); --color-emerald-500: oklch(69.6% 0.17 162.48);
/* Tier 2: Semantic mappings */ --color-primary: var(--color-blue-600); --color-surface: var(--color-slate-900); --color-surface-raised: var(--color-slate-800); --color-text: var(--color-slate-50); --color-success: var(--color-emerald-500);}
/* Usage in components */.button-primary { background-color: var(--color-primary); color: var(--color-text);}
.card { background-color: var(--color-surface-raised);}```
**Benefits**:- Design tokens maintain consistency- Semantic names convey intent- Easy theme switching (just remap tier 2)- Clear separation of concerns
## Custom Font Configuration
Configure custom fonts with variable font features:
```css@theme { /* Font families */ --font-sans: 'Inter Variable', ui-sans-serif, system-ui, sans-serif; --font-mono: 'JetBrains Mono', ui-monospace, monospace; --font-display: 'Manrope Variable', system-ui, sans-serif;
/* Variable font settings for --font-display */ --font-display--font-variation-settings: 'wght' 600;
/* OpenType features for --font-display */ --font-display--font-feature-settings: 'ss01', 'ss02', 'cv05';
/* Font weights */ --font-weight-normal: 400; --font-weight-medium: 500; --font-weight-semibold: 600; --font-weight-bold: 700;
/* Letter spacing */ --tracking-tight: -0.025em; --tracking-normal: 0em; --tracking-wide: 0.025em;}```
**Load fonts in HTML**:```html<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">```
**Usage**:```html<h1 class="font-display font-semibold tracking-tight">Aviation Dashboard</h1><code class="font-mono text-sm">ATC-1234</code>```
## Animation Keyframes
Define custom animations with `@theme inline` and `@keyframes`:
```css@theme inline { /* Simple animations */ --animate-fade-in: fade-in 0.3s ease-out; --animate-slide-up: slide-up 0.4s cubic-bezier(0.16, 1, 0.3, 1);
/* Complex animations */ --animate-beacon: beacon 2s ease-in-out infinite; --animate-pulse-glow: pulse-glow 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
/* Keyframe definitions */ @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes slide-up { from { transform: translateY(10px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
@keyframes beacon { 0%, 100% { opacity: 1; transform: scale(1); box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7); } 50% { opacity: 0.9; transform: scale(1.05); box-shadow: 0 0 0 10px rgba(59, 130, 246, 0); } }
@keyframes pulse-glow { 0%, 100% { box-shadow: 0 0 8px 2px rgba(34, 197, 94, 0.4); } 50% { box-shadow: 0 0 16px 4px rgba(34, 197, 94, 0.8); } }}```
**Usage**:```html<div class="animate-fade-in">Fades in on mount</div><div class="animate-beacon">Pulsing beacon effect</div><div class="animate-pulse-glow">Glowing status indicator</div>```
**Respecting prefers-reduced-motion**:```css@media (prefers-reduced-motion: reduce) { * { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; }}```123456789101112131415161718192021222324# Logslogs*.lognpm-debug.log*yarn-debug.log*yarn-error.log*pnpm-debug.log*lerna-debug.log*
node_modulesdistdist-ssr*.local
# Editor directories and files.vscode/*!.vscode/extensions.json.idea.DS_Store*.suo*.ntvs**.njsproj*.sln*.sw?1234567node_modulesdistbuildcoverage.idea*.logpackage-lock.json1234567{ "singleQuote": false, "tabWidth": 2, "trailingComma": "es5", "printWidth": 80, "arrowParens": "always"}12345678910111213141516171819202122232425262728293031323334353637---title: TranslateGemma Browser Translatoremoji: 🌐colorFrom: bluecolorTo: purplesdk: staticpinned: falselicense: apache-2.0short_description: High-quality translations across 56 languages with Google's TranslateGemma, running entirely in your browserapp_file: dist/index.htmlheader: minimodels: - google/translategemma-4b-it - onnx-community/translategemma-text-4b-it-ONNX---
# TranslateGemma Browser Translator
A web-based translation application powered by Google's TranslateGemma model, running entirely in your browser with Transformers.js and ONNX Runtime Web.
## ✨ Features
- 🌍 **56 Languages** - Translate between 56 different languages- 🔒 **Completely Private** - All processing happens in your browser, no data sent to servers- 📴 **Offline-Capable** - Works offline after initial model download- ⚡ **Real-time Translation** - Auto-translate with 500ms debounce- 🔗 **Shareable Links** - Share translations with URL hash parameters- 📱 **Mobile Responsive** - Optimized for both desktop and mobile devices- 💾 **Local Caching** - Model cached locally for instant subsequent loads
## 🤖 TranslateGemma
This application uses [Google's TranslateGemma](https://blog.google/technology/developers/gemma-open-models/), a state-of-the-art language model specifically designed for translation tasks. TranslateGemma is part of Google's Gemma family of open models, delivering high-quality translations across 56 languages directly in your browser using [Transformers.js](https://huggingface.co/docs/transformers.js) and ONNX Runtime Web.
## 🔒 Completely Private & Offline-Capable
Your translations are processed entirely in your browser with **no data sent to any server**. Once the model is downloaded, you can use this translator completely offline. Your text never leaves your device, ensuring complete privacy and security. The model is cached locally, so subsequent visits will load instantly without any downloads.12345678910111213141516171819202122232425262728import js from '@eslint/js'import globals from 'globals'import reactHooks from 'eslint-plugin-react-hooks'import reactRefresh from 'eslint-plugin-react-refresh'import tseslint from 'typescript-eslint'
export default tseslint.config( { ignores: ['dist'] }, { extends: [js.configs.recommended, ...tseslint.configs.recommended], files: ['**/*.{ts,tsx}'], languageOptions: { ecmaVersion: 2020, globals: globals.browser, }, plugins: { 'react-hooks': reactHooks, 'react-refresh': reactRefresh, }, rules: { ...reactHooks.configs.recommended.rules, 'react-refresh/only-export-components': [ 'warn', { allowConstantExport: true }, ], }, })123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051<!doctype html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<!-- SEO Meta Tags --> <title> TranslateGemma Browser Translator - Private & Offline Translation </title> <meta name="description" content="High-quality translations across 56 languages powered by Google's TranslateGemma model. Runs entirely in your browser with complete privacy and offline capability using Transformers.js." /> <meta name="keywords" content="translation, translator, TranslateGemma, Transformers.js, offline translator, private translation, browser translation, Gemma, ONNX" />
<!-- Open Graph Meta Tags --> <meta property="og:title" content="TranslateGemma Browser Translator" /> <meta property="og:description" content="High-quality translations across 56 languages powered by Google's TranslateGemma model, running entirely in your browser with complete privacy." /> <meta property="og:type" content="website" /> <meta property="og:image" content="/favicon.svg" />
<!-- Twitter Card Meta Tags --> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:title" content="TranslateGemma Browser Translator" /> <meta name="twitter:description" content="High-quality translations across 56 languages powered by Google's TranslateGemma model, running entirely in your browser with complete privacy." /> <meta name="twitter:image" content="/favicon.svg" />
<!-- Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Google+Sans:wght@400;500;700&display=swap" rel="stylesheet" /> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body></html>12345678910111213141516171819202122232425262728293031323334353637{ "name": "transformersjs-translategemma", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc -b && vite build", "lint": "eslint .", "preview": "vite preview", "format": "prettier --write \"src/**/*.{ts,tsx,js,jsx,json,css}\"" }, "dependencies": { "@huggingface/transformers": "^4.0.0-next.3", "idb": "^8.0.2", "lucide-react": "^0.564.0", "react": "^19.0.0", "react-dom": "^19.0.0", "react-hook-form": "^7.54.2" }, "devDependencies": { "@eslint/js": "^9.17.0", "@tailwindcss/vite": "^4.1.18", "@types/react": "^19.0.7", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^4.3.4", "eslint": "^9.17.0", "eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-refresh": "^0.4.16", "globals": "^15.14.0", "prettier": "^3.4.2", "tailwindcss": "^4.1.18", "typescript": "~5.7.2", "typescript-eslint": "^8.18.2", "vite": "^6.0.7" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import Translate from "./Translate";import { useState } from "react";import Translator from "./ai/Translator.ts";import Initialize from "./Initialize.tsx";
function App() { const [translator, setTranslator] = useState<Translator>(null); const [progress, setProgress] = useState<number>(0); const [isInitializing, setIsInitializing] = useState<boolean>(false);
const init = async () => { setIsInitializing(true); const t = Translator.getInstance(); const loaded = new Map<string, number>(); let newProgress = 0; await t.init((e) => { if (e.status === "progress") { loaded.set(e.file, e.loaded); const allLoaded = Array.from(loaded.values()).reduce( (acc: number, curr: number) => acc + curr, 0 ); const percentLoaded = Math.round((100 / Translator.size) * allLoaded); if (newProgress !== percentLoaded) { newProgress = percentLoaded; setProgress(newProgress); } } }); setTranslator(t); setIsInitializing(false); };
return ( <div className="min-h-screen bg-neutral-100 flex flex-col justify-between gap-2"> <header className="bg-white border-b border-border shadow-sm p-4"> <h1 className="text-md md:text-3xl font-sans text-center flex justify-center items-center gap-2 md:gap-6"> <span className="font-bold flex items-center justify-center gap-1"> <img src="gemma.svg" alt="Gemma Logo" className="block" style={{ width: "1.2em", height: "1.2em", }} /> <span> Translate<span className="text-primary">Gemma</span> </span> </span> <span>//</span> <span className="font-bold flex items-center justify-center gap-1"> <img src="hf-logo.svg" alt="Gemma Logo" className="block" style={{ width: "1.2em", height: "1.2em", }} /> Transformers.js </span> </h1> </header> {translator ? ( <Translate className="w-full" translator={translator} /> ) : ( <Initialize onInitialize={init} progress={progress} isInitializing={isInitializing} /> )} <footer className="p-8 pt-0 text-center text-muted-foreground text-xs md:text-sm"> <p> High-quality translations across 56 languages powered by{" "} <a href="https://blog.google/technology/developers/gemma-open-models/" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline" > Google's TranslateGemma </a>{" "} model, running entirely in your browser with{" "} <a href="https://huggingface.co/docs/transformers.js" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline" > Transformers.js </a>{" "} and complete privacy. </p> </footer> </div> );}
export default App;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import { Button } from "./theme";import cn from "./utils/classnames.ts";import { formatBytes } from "./utils/format.ts";import Translator from "./ai/Translator.ts";
interface InitializeProps { progress: number; onInitialize: () => Promise<void>; isInitializing?: boolean; className?: string;}
export default function Initialize({ progress, onInitialize, isInitializing = false, className = "",}: InitializeProps) { return ( <div className={cn("max-w-2xl mx-auto px-8", className)}> <div className="bg-white rounded-lg shadow-md p-8 border border-border"> <div className="flex flex-col items-center gap-6"> {/* Description */} <div className="space-y-4 text-left w-full"> <div> <h3 className="font-semibold text-base mb-1"> About TranslateGemma 4B </h3> <p className="text-sm text-secondary-foreground"> TranslateGemma is a family of translation models from Google, built on top of Gemma 2B. This 4B parameter model supports translations across 100+ languages with state-of-the-art quality.{" "} <a href="https://blog.google/innovation-and-ai/technology/developers-tools/translategemma/" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline" > Learn more </a> </p> </div>
<div> <h3 className="font-semibold text-base mb-1"> Completely private & offline-capable </h3> <p className="text-sm text-secondary-foreground"> Everything runs entirely in your browser with 🤗 Transformers.js and ONNX Runtime Web — no data is ever sent to a server. Once loaded, it works offline. </p> </div>
<div> <h3 className="font-semibold text-base mb-1"> Experimental — WebGPU required </h3> <p className="text-sm text-secondary-foreground"> This is experimental and requires a browser with WebGPU support and enough VRAM to run the model. </p> </div> </div>
{/* Initialize button or progress indicator */} {isInitializing ? ( <div className="w-full space-y-2"> <div className="flex justify-between items-center"> <span className="text-sm font-medium text-muted-foreground"> Loading model... </span> <span className="text-sm font-medium text-primary"> {progress}% </span> </div> <div className="w-full bg-muted rounded-full h-2 overflow-hidden"> <div className="bg-primary h-full transition-all duration-300 ease-out" style={{ width: `${progress}%` }} /> </div> <p className="text-xs text-muted-foreground text-center"> This may take a few moments. Please don't close the page. </p> </div> ) : ( <Button variant="primary" onClick={onInitialize} disabled={isInitializing} className="text-lg mt-8" > {isInitializing ? "Initializing..." : `Download TranslateGemma (${formatBytes(Translator.size)})`} </Button> )} </div> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280import { useState, useEffect, useRef } from "react";import { ArrowLeftRight, Copy, Check, Share2, Trash } from "lucide-react";import { Textarea, Button, Loader } from "./theme";import cn from "./utils/classnames.ts";import { type LanguageCode, LANGUAGES } from "./constants";import LanguageSelector from "./components/LanguageSelector";import Translator from "./ai/Translator.ts";import { formatTime, formatNumber } from "./utils/format";import { countWords } from "./utils/countWords.ts";
const MAX_INPUT_LENGTH = 1000;
interface TranslateProps { className?: string; translator: Translator;}
export default function Translate({ className = "", translator,}: TranslateProps) { // Initialize from URL hash const getInitialState = () => { const hash = window.location.hash.slice(1); // Remove the # character const params = new URLSearchParams(hash);
const sourceLang = params.get("sl"); const targetLang = params.get("tl"); const text = params.get("text");
// Validate language codes const isValidLanguage = (code: string | null): code is LanguageCode => { if (!code) return false; return LANGUAGES.some((lang) => lang.code === code); };
return { sourceLanguage: isValidLanguage(sourceLang) ? sourceLang : ("en" as LanguageCode), targetLanguage: isValidLanguage(targetLang) ? targetLang : ("de_DE" as LanguageCode), sourceText: text ? decodeURIComponent(text) : "", }; };
const initialState = getInitialState();
const [sourceText, setSourceText] = useState(initialState.sourceText); const [targetText, setTargetText] = useState(""); const [sourceLanguage, setSourceLanguage] = useState<LanguageCode>( initialState.sourceLanguage ); const [targetLanguage, setTargetLanguage] = useState<LanguageCode>( initialState.targetLanguage ); const [translating, setTranslating] = useState<boolean>(false); const [copied, setCopied] = useState<boolean>(false); const [shared, setShared] = useState<boolean>(false); const abortControllerRef = useRef<AbortController | null>(null); const [translationTime, setTranslationTime] = useState<number>(0); const [translationWords, setTranslationWords] = useState<number>(0);
const handleSwapLanguages = () => { // Swap languages setSourceLanguage(targetLanguage); setTargetLanguage(sourceLanguage);
// Swap text content setSourceText(targetText); setTargetText(sourceText); };
const handleCopy = async () => { if (!targetText) return;
try { await navigator.clipboard.writeText(targetText); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (error) { console.error("Failed to copy:", error); } };
const handleShare = async () => { try { const currentUrl = window.location.href; await navigator.clipboard.writeText(currentUrl); setShared(true); setTimeout(() => setShared(false), 2000); } catch (error) { console.error("Failed to share:", error); } };
const translate = async ( text: string, sourceLang: LanguageCode, targetLang: LanguageCode ) => { if (!text.trim()) { setTargetText(""); setTranslationTime(0); setTranslationWords(0); return; }
const started = performance.now();
if (abortControllerRef.current) { abortControllerRef.current.abort(); }
abortControllerRef.current = new AbortController(); const currentController = abortControllerRef.current;
setTranslating(true);
try { const translation = await translator.translate( text, sourceLang, targetLang );
if (!currentController.signal.aborted) { setTargetText(translation); setTranslationTime(Math.round(performance.now() - started)); setTranslationWords(countWords(text)); } } catch (error) { if (!currentController.signal.aborted) { console.error("Translation error:", error); } } finally { if (!currentController.signal.aborted) { setTranslating(false); } } };
// Update URL hash when languages or text change useEffect(() => { const params = new URLSearchParams(); params.set("sl", sourceLanguage); params.set("tl", targetLanguage); if (sourceText) { params.set("text", encodeURIComponent(sourceText)); }
const newHash = `#${params.toString()}`; window.history.replaceState({}, "", newHash); }, [sourceLanguage, targetLanguage, sourceText]);
useEffect(() => { const timer = setTimeout(() => { translate(sourceText, sourceLanguage, targetLanguage); }, 500);
return () => { clearTimeout(timer); }; }, [sourceText, sourceLanguage, targetLanguage]);
return ( <div className={cn("max-w-6xl mx-auto p-2 md:p-4 relative", className)}> <div className="flex flex-col md:flex-row w-full gap-4 md:gap-8"> <div className="flex flex-col gap-3 w-full md:w-1/2 relative"> <LanguageSelector value={sourceLanguage} onChange={setSourceLanguage} /> <Textarea value={sourceText} onChange={(e) => setSourceText(e.target.value)} placeholder="Enter text to translate..." className="h-48 md:h-70 pb-10" variant="default" maxLength={MAX_INPUT_LENGTH} /> <div className="p-2 flex justify-between items-center -mt-4"> <p className="text-xs text-muted-foreground opacity-70"> {formatNumber(sourceText.length)} /{" "} {formatNumber(MAX_INPUT_LENGTH)} </p> <div className="flex gap-2"> <button onClick={handleShare} className="p-2 text-muted-foreground hover:text-primary hover:bg-muted rounded-md transition-colors" aria-label="Share translation" > {shared ? ( <span className="flex text-xs gap-2"> link copied <Check className="w-4 h-4 text-primary" /> </span> ) : ( <Share2 className="w-4 h-4" /> )} </button> <button onClick={() => setSourceText("")} className="p-2 text-muted-foreground hover:text-primary hover:bg-muted rounded-md transition-colors" aria-label="clear text" > <Trash className="w-4 h-4" /> </button> </div> </div> </div>
<div className="hidden md:block absolute left-1/2 top-5 -translate-x-1/2"> <Button variant="ghost" icon={ArrowLeftRight} onClick={handleSwapLanguages} aria-label="Swap languages" /> </div>
<div className="flex md:hidden justify-center -my-2"> <Button variant="ghost" icon={ArrowLeftRight} onClick={handleSwapLanguages} aria-label="Swap languages" className="rotate-90" /> </div>
<div className="flex flex-col gap-3 w-full md:w-1/2"> <div className="flex items-center justify-between"> <LanguageSelector value={targetLanguage} onChange={setTargetLanguage} /> {translating && <Loader size={20} />} </div> <div> <Textarea value={targetText} disabled placeholder="Translation will appear here..." className="h-48 md:h-70" variant="default" /> <div className="p-2 flex justify-between items-center -mt-4"> {translationTime > 0 ? ( <p className="text-xs text-muted-foreground opacity-70"> Translated <b>{formatNumber(translationWords)} words</b> in{" "} <b>{formatTime(translationTime)}</b> </p> ) : ( <p /> )} <div> <button onClick={handleCopy} className="p-2 text-muted-foreground hover:text-primary hover:bg-muted rounded-md transition-colors" aria-label="Copy translation" > {copied ? ( <span className="flex text-xs gap-2"> translation copied <Check className="w-4 h-4 text-primary" /> </span> ) : ( <Copy className="w-4 h-4" /> )} </button> </div> </div> </div> </div> </div> </div> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import { pipeline, DataType } from "@huggingface/transformers";import { ProgressCallback } from "../types/transformers.ts";
class Translator { private static instance: Translator | null = null; private pipeline: any = null; private static modelId: string = "onnx-community/translategemma-text-4b-it-ONNX"; private static dtype: DataType = "q4"; public static size: number = 3111894696;
private constructor() {}
public static getInstance(): Translator { if (!Translator.instance) { Translator.instance = new Translator(); } return Translator.instance; }
public async init(onProgress?: ProgressCallback) { if (this.pipeline) return;
this.pipeline = await pipeline("text-generation", Translator.modelId, { progress_callback: onProgress, device: "webgpu", dtype: Translator.dtype, }); }
public async translate( text: string, sourceLang: string, targetLang: string ): Promise<string> { if (!this.pipeline) { throw new Error("Translator not initialized. Call init() first."); }
console.log(`Translating from ${sourceLang} to ${targetLang}`, text);
const messages = [ { role: "user", content: [ { type: "text", source_lang_code: sourceLang, target_lang_code: targetLang, text, }, ], }, ];
const output = await this.pipeline(messages, { max_new_tokens: 1024, });
return output[0].generated_text.pop().content; }}
export default Translator;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116import { useState, useRef, useEffect } from "react";import { ChevronDown } from "lucide-react";import { LANGUAGES, type LanguageCode, LANGUAGES_WITH_AUTO,} from "../constants";
interface LanguageSelectorProps { value: LanguageCode; onChange: (language: LanguageCode) => void; includeAuto?: boolean;}
export default function LanguageSelector({ value, onChange, includeAuto = false,}: LanguageSelectorProps) { const [isOpen, setIsOpen] = useState(false); const [search, setSearch] = useState(""); const containerRef = useRef<HTMLDivElement>(null); const searchInputRef = useRef<HTMLInputElement>(null);
const languages = includeAuto ? LANGUAGES_WITH_AUTO : LANGUAGES;
const getLanguageDisplay = (code: LanguageCode) => { return languages.find((lang) => lang.code === code)?.name || code; };
const filterLanguages = (searchTerm: string) => { const searchLower = searchTerm.toLowerCase(); return languages.filter( (lang) => lang.name.toLowerCase().includes(searchLower) || lang.code.toLowerCase().includes(searchLower) ); };
const filteredLanguages = search ? filterLanguages(search) : languages;
const handleSelect = (language: LanguageCode) => { onChange(language); setIsOpen(false); setSearch(""); };
useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if ( containerRef.current && !containerRef.current.contains(event.target as Node) ) { setIsOpen(false); setSearch(""); } };
if (isOpen) { document.addEventListener("mousedown", handleClickOutside); setTimeout(() => searchInputRef.current?.focus(), 0); }
return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [isOpen]);
return ( <div className="relative" ref={containerRef}> <button onClick={() => setIsOpen(!isOpen)} className="inline-flex items-center gap-2 px-3 py-2 text-sm font-medium text-primary hover:bg-muted rounded-md transition-colors" > <span>{getLanguageDisplay(value)}</span> <ChevronDown className={`w-4 h-4 transition-transform ${isOpen ? "rotate-180" : ""}`} /> </button>
{isOpen && ( <div className="absolute top-full left-0 mt-2 w-64 bg-white border border-border rounded-md shadow-lg z-50"> <div className="p-2 border-b border-border"> <input ref={searchInputRef} type="text" placeholder="Search languages..." value={search} onChange={(e) => setSearch(e.target.value)} className="w-full px-3 py-2 text-sm border border-border rounded-md focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" /> </div>
<div className="max-h-60 overflow-auto"> {filteredLanguages.map((lang) => ( <button key={lang.code} onClick={() => handleSelect(lang.code)} className={`w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors ${ value === lang.code ? "bg-primary-50 text-primary-800" : "" }`} > {lang.name} </button> ))} {filteredLanguages.length === 0 && ( <div className="px-3 py-4 text-sm text-muted-foreground text-center"> No languages found </div> )} </div> </div> )} </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172export const LANGUAGES = [ { code: "ar_EG", name: "Arabic (Egypt)" }, { code: "ar_SA", name: "Arabic (Saudi Arabia)" }, { code: "bg_BG", name: "Bulgarian" }, { code: "bn_IN", name: "Bengali" }, { code: "ca_ES", name: "Catalan" }, { code: "cs_CZ", name: "Czech" }, { code: "da_DK", name: "Danish" }, { code: "de_DE", name: "German" }, { code: "el_GR", name: "Greek" }, { code: "en", name: "English" }, { code: "es_XX", name: "Spanish" }, { code: "et_EE", name: "Estonian" }, { code: "fa_IR", name: "Persian" }, { code: "fi_FI", name: "Finnish" }, { code: "fil_PH", name: "Filipino" }, { code: "fr_CA", name: "French (Canada)" }, { code: "fr_FR", name: "French" }, { code: "gu_IN", name: "Gujarati" }, { code: "he_IL", name: "Hebrew" }, { code: "hi_IN", name: "Hindi" }, { code: "hr_HR", name: "Croatian" }, { code: "hu_HU", name: "Hungarian" }, { code: "id_ID", name: "Indonesian" }, { code: "is_IS", name: "Icelandic" }, { code: "it_IT", name: "Italian" }, { code: "ja_JP", name: "Japanese" }, { code: "kn_IN", name: "Kannada" }, { code: "ko_KR", name: "Korean" }, { code: "lt_LT", name: "Lithuanian" }, { code: "lv_LV", name: "Latvian" }, { code: "ml_IN", name: "Malayalam" }, { code: "mr_IN", name: "Marathi" }, { code: "nl_NL", name: "Dutch" }, { code: "no_NO", name: "Norwegian" }, { code: "pa_IN", name: "Punjabi" }, { code: "pl_PL", name: "Polish" }, { code: "pt_BR", name: "Portuguese (Brazil)" }, { code: "pt_PT", name: "Portuguese (Portugal)" }, { code: "ro_RO", name: "Romanian" }, { code: "ru_RU", name: "Russian" }, { code: "sk_SK", name: "Slovak" }, { code: "sl_SI", name: "Slovenian" }, { code: "sr_RS", name: "Serbian" }, { code: "sv_SE", name: "Swedish" }, { code: "sw_KE", name: "Swahili" }, { code: "sw_TZ", name: "Swahili (Tanzania)" }, { code: "ta_IN", name: "Tamil" }, { code: "te_IN", name: "Telugu" }, { code: "th_TH", name: "Thai" }, { code: "tr_TR", name: "Turkish" }, { code: "uk_UA", name: "Ukrainian" }, { code: "ur_PK", name: "Urdu" }, { code: "vi_VN", name: "Vietnamese" }, { code: "zh_CN", name: "Chinese (Simplified)" }, { code: "zh_TW", name: "Chinese (Traditional)" }, { code: "zu_ZA", name: "Zulu" },] as const;
export const LANGUAGES_WITH_AUTO = [ { code: "auto", name: "Auto", }, ...LANGUAGES,] as const;
export type LanguageCode = (typeof LANGUAGES_WITH_AUTO)[number]["code"];
export const getLanguageName = (code: LanguageCode): string => { return LANGUAGES.find((lang) => lang.code === code)?.name || code;};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566@import "tailwindcss";
@theme { /* Custom font family - Google Sans */ --font-sans: "Google Sans", system-ui, -apple-system, sans-serif;
/* Google Translate inspired primary colors */ --color-primary-50: #e8f0fe; --color-primary-100: #d3e3fd; --color-primary-200: #aecbfa; --color-primary-300: #8ab4f8; --color-primary-400: #669df6; --color-primary-500: #1a73e8; /* Main primary */ --color-primary-600: #1557b0; --color-primary-700: #0d47a1; --color-primary-800: #0842a0; --color-primary-900: #0b57d0;
/* Semantic colors */ --color-primary: var(--color-primary-500); --color-primary-foreground: #ffffff; --color-secondary: oklch(95% 0.01 262); --color-secondary-foreground: oklch(20% 0.05 262); --color-muted: #f1f3f4; --color-muted-foreground: #5f6368; --color-accent: oklch(95% 0.01 220); --color-accent-foreground: oklch(20% 0.05 220); --color-destructive: oklch(58% 0.24 27); --color-destructive-foreground: oklch(98% 0.002 27); --color-border: #dadce0; --color-input: oklch(90% 0.01 262); --color-ring: var(--color-primary-500);
/* Font sizes - increased base size */ --font-size-xs: 0.8125rem; /* 13px */ --font-size-sm: 0.9375rem; /* 15px */ --font-size-base: 1.0625rem; /* 17px - increased from default 16px */ --font-size-lg: 1.1875rem; /* 19px */ --font-size-xl: 1.3125rem; /* 21px */ --font-size-2xl: 1.5625rem; /* 25px */ --font-size-3xl: 1.9375rem; /* 31px */ --font-size-4xl: 2.3125rem; /* 37px */ --font-size-5xl: 3.0625rem; /* 49px */ --font-size-6xl: 3.8125rem; /* 61px */ --font-size-7xl: 4.8125rem; /* 77px */ --font-size-8xl: 6.0625rem; /* 97px */ --font-size-9xl: 8.0625rem; /* 129px */
/* Spacing base */ --spacing: 0.25rem;}
body { margin: 0; padding: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;}
* { box-sizing: border-box;}
#root { min-height: 100vh;}12345678910import { StrictMode } from "react";import { createRoot } from "react-dom/client";import "./index.css";import App from "./App.tsx";
createRoot(document.getElementById("root")!).render( <StrictMode> <App /> </StrictMode>);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import { ButtonHTMLAttributes, DetailedHTMLProps, ReactNode } from "react";import { LucideIcon } from "lucide-react";import cn from "../../utils/classnames.ts";
interface ButtonProps extends DetailedHTMLProps< ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> { variant?: | "primary" | "outlined" | "pill" | "pill-selected" | "text" | "ghost"; icon?: LucideIcon; iconPosition?: "left" | "right"; children?: ReactNode;}
export default function Button({ variant = "primary", icon: Icon, iconPosition = "left", children, className = "", ...props}: ButtonProps) { const baseClasses = "inline-flex items-center justify-center font-medium text-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2";
const variantClasses = { primary: "bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 rounded-md shadow-sm hover:shadow focus:ring-primary/50", outlined: "bg-transparent text-primary hover:bg-muted active:bg-primary-50 border border-border rounded-[48px] focus:ring-primary/30", pill: "bg-transparent text-primary hover:bg-primary-50 active:bg-muted border border-border rounded-[48px] focus:ring-primary/30", "pill-selected": "bg-primary-100 text-primary-800 hover:bg-primary-200 active:bg-primary-200 border border-primary-100 rounded-[48px] shadow-sm focus:ring-primary-800/30", text: "bg-transparent text-primary hover:bg-muted active:bg-primary-50 rounded-md focus:ring-primary/30", ghost: "bg-transparent text-muted-foreground hover:bg-muted hover:text-primary active:bg-primary-50 rounded-md focus:ring-primary/30", };
const sizeClasses = { primary: "[padding:0.625em_1.5em] [gap:0.5em]", outlined: "[padding:0.5em_0.75em] [gap:0.5em]", pill: "[padding:0.5em_0.75em] [gap:0.5em]", "pill-selected": "[padding:0.5em_0.75em] [gap:0.5em]", text: "[padding:0.375em_0.5em] [gap:0.5em]", ghost: "[padding:0.5em_0.75em] [gap:0.5em]", };
const disabledClasses = "disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-current disabled:hover:shadow-none";
return ( <button className={cn( "cursor-pointer", baseClasses, variantClasses[variant], sizeClasses[variant], disabledClasses, className )} {...props} > {Icon && iconPosition === "left" && ( <Icon className="[width:1.25em] [height:1.25em]" /> )} {children} {Icon && iconPosition === "right" && ( <Icon className="[width:1.25em] [height:1.25em]" /> )} </button> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import { DetailedHTMLProps, TextareaHTMLAttributes, useMemo } from "react";import cn from "../../utils/classnames";
interface TextareaProps extends DetailedHTMLProps< TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement> { variant?: "default" | "minimal"; error?: boolean;}
export default function Textarea({ variant = "default", error = false, className = "", value, ...props}: TextareaProps) { const baseClasses = "w-full font-sans transition-all duration-200 resize-none focus:outline-none";
const variantClasses = { default: "px-4 py-3 border border-border rounded-md bg-white hover:border-primary-300 focus:border-primary focus:ring-2 focus:ring-primary/20", minimal: "px-4 py-3 border-0 bg-transparent hover:bg-muted/30 focus:bg-white focus:shadow-sm rounded-md", };
const errorClasses = error ? "border-destructive focus:border-destructive focus:ring-destructive/20" : "";
const disabledClasses = "disabled:cursor-default";
const fontSizeClass = useMemo(() => { const length = typeof value === "string" ? value.length : 0; console.log(length);
if (length === 0) return "text-2xl"; if (length < 50) return "text-2xl"; if (length < 200) return "text-xl"; if (length < 300) return "text-lg"; return "text-base"; }, [value]);
return ( <textarea className={cn( baseClasses, variantClasses[variant], errorClasses, disabledClasses, fontSizeClass, className )} value={value} {...props} /> );}123export { default as Button } from "./button/Button";export { default as Textarea } from "./form/Textarea";export { default as Loader } from "./misc/Loader";123456789101112131415import { Loader2 } from "lucide-react";
interface LoaderProps { size?: number; className?: string;}
export default function Loader({ size = 20, className = "" }: LoaderProps) { return ( <Loader2 className={`animate-spin text-primary ${className}`} style={{ width: size, height: size }} /> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677export type InitiateProgressInfo = { status: "initiate"; /** * The model id or directory path. */ name: string; /** * The name of the file. */ file: string;};export type DownloadProgressInfo = { status: "download"; /** * The model id or directory path. */ name: string; /** * The name of the file. */ file: string;};export type ProgressStatusInfo = { status: "progress"; /** * The model id or directory path. */ name: string; /** * The name of the file. */ file: string; /** * A number between 0 and 100. */ progress: number; /** * The number of bytes loaded. */ loaded: number; /** * The total number of bytes to be loaded. */ total: number;};export type DoneProgressInfo = { status: "done"; /** * The model id or directory path. */ name: string; /** * The name of the file. */ file: string;};export type ReadyProgressInfo = { status: "ready"; /** * The loaded task. */ task: string; /** * The loaded model. */ model: string;};export type ProgressInfo = | InitiateProgressInfo | DownloadProgressInfo | ProgressStatusInfo | DoneProgressInfo | ReadyProgressInfo;/** * A callback function that is called with progress information. */export type ProgressCallback = (progressInfo: ProgressInfo) => void;12345678910111213const cn = (...classes: Array<Record<string, boolean> | string>): string => classes .map((entry) => typeof entry === "string" ? entry : Object.entries(entry || {}) .filter(([, append]) => append) .map(([cl]) => cl) .join(" ") ) .filter((e) => e !== "") .join(" ");export default cn;12345678910111213export function countWords(text: string): number { if (!text || text.trim().length === 0) { return 0; }
// Remove extra whitespace and split by whitespace const words = text .trim() .split(/\s+/) .filter((word) => word.length > 0);
return words.length;}12345678910111213141516171819202122232425262728export function formatBytes(bytes: number, decimals: number = 1): string { if (bytes === 0) return "0 Bytes";
const k = 1024; const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"]; const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))}${sizes[i]}`;}
export function formatTime(ms: number): string { if (ms < 1000) { return `${Math.round(ms)}ms`; }
const seconds = ms / 1000; if (seconds < 60) { return `${seconds.toFixed(1)}s`; }
const minutes = Math.floor(seconds / 60); const remainingSeconds = Math.round(seconds % 60); return `${minutes}m ${remainingSeconds}s`;}
export function formatNumber(num: number): string { return new Intl.NumberFormat("en-US").format(num);}1/// <reference types="vite/client" />1234567891011121314151617181920212223242526{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true,
/* Bundler mode */ "moduleResolution": "Bundler", "allowImportingTsExtensions": true, "isolatedModules": true, "moduleDetection": "force", "noEmit": true, "jsx": "react-jsx",
/* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, "strictNullChecks": false }, "include": ["src"]}1{"root":["./src/app.tsx","./src/initialize.tsx","./src/translate.tsx","./src/constants.ts","./src/main.tsx","./src/vite-env.d.ts","./src/ai/translator.ts","./src/components/languageselector.tsx","./src/theme/index.ts","./src/theme/button/button.tsx","./src/theme/form/textarea.tsx","./src/theme/misc/loader.tsx","./src/types/transformers.ts","./src/utils/classnames.ts","./src/utils/countwords.ts","./src/utils/format.ts"],"version":"5.7.3"}1234567{ "files": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" } ]}1234567891011121314151617181920212223{ "compilerOptions": { "target": "ES2022", "lib": ["ES2023"], "module": "ESNext", "skipLibCheck": true,
/* Bundler mode */ "moduleResolution": "Bundler", "allowImportingTsExtensions": true, "isolatedModules": true, "moduleDetection": "force", "noEmit": true,
/* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, "include": ["vite.config.ts"]}1{"root":["./vite.config.ts"],"version":"5.7.3"}12345678import { defineConfig } from 'vite'import react from '@vitejs/plugin-react'import tailwindcss from '@tailwindcss/vite'
// https://vite.dev/config/export default defineConfig({ plugins: [react(), tailwindcss()],}).agents/skills/tailwind-v4/SKILL.mdAdded+225
.agents/skills/tailwind-v4/references/dark-mode.mdAdded+458
.agents/skills/tailwind-v4/references/setup.mdAdded+264
.agents/skills/tailwind-v4/references/theming.mdAdded+492
.gitignoreAdded+24
.prettierignoreAdded+7
.prettierrcAdded+7
README.mdAdded+37
eslint.config.jsAdded+28
index.htmlAdded+51
package-lock.jsonAdded
package.jsonAdded+37
public/favicon.svgAdded
public/gemma.svgAdded
public/hf-logo.svgAdded
src/App.tsxAdded+103
src/Initialize.tsxAdded+104
src/Translate.tsxAdded+280
src/ai/Translator.tsAdded+64
src/components/LanguageSelector.tsxAdded+116
src/constants.tsAdded+72
src/index.cssAdded+66
src/main.tsxAdded+10
src/theme/button/Button.tsxAdded+78
src/theme/form/Textarea.tsxAdded+60
src/theme/index.tsAdded+3
src/theme/misc/Loader.tsxAdded+15
src/types/transformers.tsAdded+77
src/utils/classnames.tsAdded+13
src/utils/countWords.tsAdded+13
src/utils/format.tsAdded+28
src/vite-env.d.tsAdded+1
tsconfig.app.jsonAdded+26
tsconfig.app.tsbuildinfoAdded+1
tsconfig.jsonAdded+7
tsconfig.node.jsonAdded+23
tsconfig.node.tsbuildinfoAdded+1
vite.config.tsAdded+8