Imamverdi Behbudlu
feat(i18n): complete English internationalization for UI and pipeline engine
502e615 Download src/components/FormbricksTranslator.jsx from imamverdibehbudlu/consensus-ai-localization: direct link, hf CLI and curl.
- Browser
- Download file 17.8 kB
-
https://huggingface.co/spaces/imamverdibehbudlu/consensus-ai-localization/resolve/main/src/components/FormbricksTranslator.jsx
- Command line
-
hf download hf://spaces/imamverdibehbudlu/consensus-ai-localization/src/components/FormbricksTranslator.jsx
-
curl -L -o FormbricksTranslator.jsx https://huggingface.co/spaces/imamverdibehbudlu/consensus-ai-localization/resolve/main/src/components/FormbricksTranslator.jsx
17.8 kB
| import React, { useState } from 'react'; | |
| import { runPipelineForSegment } from '../utils/pipeline'; | |
| import { | |
| Globe, Play, Search, Save, Settings, | |
| CheckCircle2, XCircle, Loader2, Info, Download | |
| } from 'lucide-react'; | |
| const LANGUAGES = [ | |
| { code: 'FR', locale: 'fr-FR', name: 'French' }, | |
| { code: 'NL', locale: 'nl-NL', name: 'Dutch' }, | |
| { code: 'DE', locale: 'de-DE', name: 'German' }, | |
| { code: 'ES', locale: 'es-ES', name: 'Spanish' }, | |
| { code: 'PT', locale: 'pt-PT', name: 'Portuguese (Portugal)' }, | |
| { code: 'BR', locale: 'pt-BR', name: 'Portuguese (Brazil)' }, | |
| { code: 'HU', locale: 'hu-HU', name: 'Hungarian' }, | |
| { code: 'CS', locale: 'cs-CZ', name: 'Czech' }, | |
| { code: 'PL', locale: 'pl-PL', name: 'Polish' }, | |
| { code: 'IT', locale: 'it-IT', name: 'Italian' }, | |
| { code: 'EL', locale: 'el-GR', name: 'Greek' }, | |
| { code: 'AZ', locale: 'az-AZ', name: 'Azerbaijani' }, | |
| { code: 'TR', locale: 'tr-TR', name: 'Turkish' }, | |
| { code: 'RU', locale: 'ru-RU', name: 'Russian' } | |
| ]; | |
| export default function FormbricksTranslator() { | |
| const [surveyId, setSurveyId] = useState(''); | |
| const [surveyData, setSurveyData] = useState(null); | |
| const [isFetching, setIsFetching] = useState(false); | |
| const [error, setError] = useState(null); | |
| const [selectedLocales, setSelectedLocales] = useState([]); | |
| const [translationStatus, setTranslationStatus] = useState('idle'); // idle, translating, complete | |
| const [progress, setProgress] = useState({ current: 0, total: 0, details: '' }); | |
| const [isSyncing, setIsSyncing] = useState(false); | |
| const [syncStatus, setSyncStatus] = useState(null); | |
| const extractDefaultTexts = (obj, paths = [], currentPath = '') => { | |
| let results = []; | |
| if (!obj || typeof obj !== 'object') return results; | |
| if (obj.hasOwnProperty('default') && typeof obj.default === 'string') { | |
| results.push({ | |
| path: currentPath, | |
| text: obj.default, | |
| parentRef: obj | |
| }); | |
| } | |
| for (const key in obj) { | |
| if (typeof obj[key] === 'object') { | |
| const nextPath = currentPath ? `${currentPath}.${key}` : key; | |
| results = results.concat(extractDefaultTexts(obj[key], paths, nextPath)); | |
| } | |
| } | |
| return results; | |
| }; | |
| const fetchSurvey = async () => { | |
| if (!surveyId.trim()) return; | |
| // Extract ID if URL is pasted | |
| let finalId = surveyId.trim(); | |
| if (finalId.includes('surveys/')) { | |
| const parts = finalId.split('surveys/'); | |
| finalId = parts[1].split('/')[0]; | |
| } | |
| setIsFetching(true); | |
| setError(null); | |
| setSurveyData(null); | |
| try { | |
| const res = await fetch(`/api/formbricks/survey/${finalId}`); | |
| const data = await res.json(); | |
| if (!res.ok) { | |
| throw new Error(data.error || 'Failed to fetch survey'); | |
| } | |
| const fetchedData = data.data || data; | |
| // Check if we have a locally cached translated version | |
| const cached = localStorage.getItem(`fb_cached_survey_${finalId}`); | |
| if (cached) { | |
| try { | |
| const parsedCache = JSON.parse(cached); | |
| setSurveyData(parsedCache); | |
| setTranslationStatus('complete'); | |
| setSyncStatus(null); | |
| } catch (e) { | |
| setSurveyData(fetchedData); | |
| } | |
| } else { | |
| setSurveyData(fetchedData); | |
| } | |
| } catch (err) { | |
| setError(err.message); | |
| } finally { | |
| setIsFetching(false); | |
| } | |
| }; | |
| const startTranslation = async () => { | |
| if (!surveyData || selectedLocales.length === 0) return; | |
| setTranslationStatus('translating'); | |
| setError(null); | |
| setSyncStatus(null); | |
| const cloneData = JSON.parse(JSON.stringify(surveyData)); | |
| const defaultTexts = extractDefaultTexts(cloneData); | |
| const totalSteps = defaultTexts.length * selectedLocales.length; | |
| let completedSteps = 0; | |
| setProgress({ current: 0, total: totalSteps, details: 'Starting translation pipeline...' }); | |
| try { | |
| for (const locale of selectedLocales) { | |
| const langObj = LANGUAGES.find(l => l.locale === locale) || { name: locale }; | |
| for (const item of defaultTexts) { | |
| setProgress({ | |
| current: completedSteps + 1, | |
| total: totalSteps, | |
| details: `[${locale}] Translating: ${item.text.substring(0, 30)}...` | |
| }); | |
| if (!item.text.trim()) { | |
| completedSteps++; | |
| continue; | |
| } | |
| const targetCode = langObj.code || locale.split('-')[0].toUpperCase(); | |
| const result = await runPipelineForSegment( | |
| { original: item.text }, | |
| targetCode, | |
| {}, | |
| false, | |
| "This is a Formbricks survey element.", | |
| "MARKDOWN" | |
| ); | |
| let currentRef = cloneData; | |
| const pathParts = item.path.split('.'); | |
| for (const part of pathParts) { | |
| currentRef = currentRef[part]; | |
| } | |
| currentRef[locale] = result.claude?.final_translation || result.deepl || item.text; | |
| completedSteps++; | |
| await new Promise(r => setTimeout(r, 250)); | |
| } | |
| if (cloneData.languages) { | |
| const hasLang = cloneData.languages.find(l => l.language?.code === locale || l.code === locale); | |
| if (!hasLang) { | |
| console.warn(`Language ${locale} should be activated in Formbricks dashboard.`); | |
| } | |
| } | |
| } | |
| if (cloneData.id) { | |
| localStorage.setItem(`fb_cached_survey_${cloneData.id}`, JSON.stringify(cloneData)); | |
| } | |
| setSurveyData(cloneData); | |
| setTranslationStatus('complete'); | |
| setProgress({ current: totalSteps, total: totalSteps, details: 'Translation complete! (Saved to local cache)' }); | |
| } catch (err) { | |
| console.error(err); | |
| setError(`Translation Error: ${err.message}`); | |
| setTranslationStatus('idle'); | |
| } | |
| }; | |
| const syncSurvey = async () => { | |
| if (!surveyData) return; | |
| setIsSyncing(true); | |
| setSyncStatus(null); | |
| try { | |
| const res = await fetch(`/api/formbricks/survey/${surveyData.id}`, { | |
| method: 'PUT', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify(surveyData) | |
| }); | |
| const data = await res.json(); | |
| if (!res.ok) { | |
| const detailMsg = data.details ? (typeof data.details === 'string' ? data.details : JSON.stringify(data.details)) : ''; | |
| throw new Error(`${data.error || 'Update failed'} ${detailMsg ? ': ' + detailMsg : ''}`); | |
| } | |
| setSyncStatus('success'); | |
| } catch (err) { | |
| setSyncStatus('error'); | |
| setError(`Sync Error: ${err.message}`); | |
| } finally { | |
| setIsSyncing(false); | |
| } | |
| }; | |
| const downloadJson = () => { | |
| if (!surveyData) return; | |
| const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(surveyData, null, 2)); | |
| const downloadAnchor = document.createElement('a'); | |
| downloadAnchor.setAttribute("href", dataStr); | |
| downloadAnchor.setAttribute("download", `formbricks_survey_${surveyData.id}_translated.json`); | |
| document.body.appendChild(downloadAnchor); | |
| downloadAnchor.click(); | |
| downloadAnchor.remove(); | |
| }; | |
| const clearLocalCache = () => { | |
| if (!surveyData?.id) return; | |
| if (window.confirm("Do you want to clear the locally cached translations for this survey and reset?")) { | |
| localStorage.removeItem(`fb_cached_survey_${surveyData.id}`); | |
| fetchSurvey(); | |
| } | |
| }; | |
| const toggleLocale = (locale) => { | |
| if (selectedLocales.includes(locale)) { | |
| setSelectedLocales(selectedLocales.filter(l => l !== locale)); | |
| } else { | |
| setSelectedLocales([...selectedLocales, locale]); | |
| } | |
| }; | |
| return ( | |
| <div className="glass-panel" style={{ padding: '2rem', minHeight: '80vh', margin: '2rem' }}> | |
| <div style={{ marginBottom: '2rem' }}> | |
| <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.5rem' }}> | |
| <Globe size={24} style={{ color: 'var(--accent-blue)' }} /> | |
| Formbricks Survey Localizer | |
| </h2> | |
| <p style={{ color: 'var(--text-secondary)' }}> | |
| Seamlessly localize Formbricks surveys across multiple languages using multi-agent consensus. | |
| </p> | |
| </div> | |
| <div style={{ display: 'grid', gap: '2rem', gridTemplateColumns: '1fr 350px' }}> | |
| {/* Left Panel: Input & Progress */} | |
| <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}> | |
| <div className="editor-card" style={{ padding: '1.5rem' }}> | |
| <h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}> | |
| <Search size={18} /> Survey ID or URL | |
| </h3> | |
| <div style={{ display: 'flex', gap: '0.5rem' }}> | |
| <input | |
| type="text" | |
| className="input" | |
| placeholder="https://app.formbricks.com/surveys/... or survey ID" | |
| value={surveyId} | |
| onChange={(e) => setSurveyId(e.target.value)} | |
| style={{ flex: 1 }} | |
| /> | |
| <button | |
| className="btn btn-primary" | |
| onClick={fetchSurvey} | |
| disabled={isFetching || !surveyId.trim()} | |
| > | |
| {isFetching ? <Loader2 size={18} className="spin" /> : 'Fetch'} | |
| </button> | |
| </div> | |
| {error && ( | |
| <div style={{ marginTop: '1rem', padding: '1rem', background: 'rgba(239, 68, 68, 0.1)', color: '#ef4444', borderRadius: '8px', fontSize: '0.875rem' }}> | |
| Error: {error} | |
| </div> | |
| )} | |
| </div> | |
| {surveyData && ( | |
| <div className="editor-card" style={{ padding: '1.5rem' }}> | |
| <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}> | |
| <h3 style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}> | |
| <Info size={18} /> Survey Details | |
| </h3> | |
| <span style={{ fontSize: '0.75rem', background: 'rgba(255,255,255,0.1)', padding: '0.2rem 0.5rem', borderRadius: '4px' }}> | |
| ID: {surveyData.id} | |
| </span> | |
| </div> | |
| <div style={{ background: 'rgba(0,0,0,0.2)', padding: '1rem', borderRadius: '8px', marginBottom: '1.5rem' }}> | |
| <strong>Title:</strong> {surveyData?.name || 'Untitled Survey'} <br/> | |
| <strong>Question Count:</strong> {surveyData?.questions?.length || surveyData?.blocks?.length || 0} <br/> | |
| <strong>Extracted Translatable Blocks:</strong> {extractDefaultTexts(surveyData).length} <br/> | |
| <div style={{ marginTop: '0.75rem', padding: '0.75rem', background: 'rgba(59, 130, 246, 0.1)', border: '1px solid rgba(59, 130, 246, 0.3)', borderRadius: '6px', fontSize: '0.8rem', color: '#93c5fd' }}> | |
| 💡 <strong>Configured Survey Languages:</strong> {surveyData?.languages?.map(l => l.language?.code || l.code).join(', ') || 'No secondary languages configured'} <br/> | |
| <span style={{ opacity: 0.8 }}>Ensure target languages are enabled in your Formbricks survey dashboard before syncing back.</span> | |
| </div> | |
| </div> | |
| {translationStatus === 'translating' && ( | |
| <div style={{ marginBottom: '1.5rem' }}> | |
| <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.875rem', marginBottom: '0.5rem' }}> | |
| <span>{progress.details}</span> | |
| <span>{progress.current} / {progress.total}</span> | |
| </div> | |
| <div style={{ width: '100%', height: '8px', background: 'rgba(255,255,255,0.1)', borderRadius: '4px', overflow: 'hidden' }}> | |
| <div style={{ width: `${(progress.current / Math.max(1, progress.total)) * 100}%`, height: '100%', background: 'var(--accent-emerald)', transition: 'width 0.3s' }}></div> | |
| </div> | |
| </div> | |
| )} | |
| <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}> | |
| <button | |
| className="btn btn-primary" | |
| onClick={startTranslation} | |
| disabled={translationStatus === 'translating' || selectedLocales.length === 0} | |
| style={{ flex: 1, display: 'flex', justifyContent: 'center', gap: '0.5rem', minWidth: '160px' }} | |
| > | |
| {translationStatus === 'translating' ? <Loader2 size={18} className="spin" /> : <Play size={18} />} | |
| Start Localization | |
| </button> | |
| <button | |
| className="btn btn-secondary" | |
| onClick={syncSurvey} | |
| disabled={translationStatus !== 'complete' || isSyncing} | |
| style={{ flex: 1, display: 'flex', justifyContent: 'center', gap: '0.5rem', minWidth: '160px', background: translationStatus === 'complete' ? 'rgba(16, 185, 129, 0.15)' : '', color: translationStatus === 'complete' ? '#10b981' : '' }} | |
| > | |
| {isSyncing ? <Loader2 size={18} className="spin" /> : <Save size={18} />} | |
| {syncStatus === 'success' ? 'Synced to Formbricks!' : 'Sync to Formbricks'} | |
| </button> | |
| <button | |
| className="btn btn-secondary" | |
| onClick={downloadJson} | |
| disabled={!surveyData} | |
| style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', background: 'rgba(59, 130, 246, 0.15)', color: '#60a5fa', borderColor: 'rgba(59, 130, 246, 0.4)' }} | |
| title="Download translated JSON file" | |
| > | |
| <Download size={18} /> | |
| <span>Download JSON</span> | |
| </button> | |
| {surveyData?.id && localStorage.getItem(`fb_cached_survey_${surveyData.id}`) && ( | |
| <button | |
| className="btn btn-secondary" | |
| onClick={clearLocalCache} | |
| style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', fontSize: '0.75rem', opacity: 0.7 }} | |
| title="Reset cached translations and reload from server" | |
| > | |
| <span>Reset Cache</span> | |
| </button> | |
| )} | |
| </div> | |
| </div> | |
| )} | |
| </div> | |
| {/* Right Panel: Languages */} | |
| <div className="editor-card" style={{ padding: '1.5rem', height: 'fit-content' }}> | |
| <h3 style={{ marginBottom: '1rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}> | |
| <Settings size={18} /> Target Locales | |
| </h3> | |
| <p style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '1rem' }}> | |
| Select target languages to translate: | |
| </p> | |
| <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem', maxHeight: '400px', overflowY: 'auto', paddingRight: '0.5rem' }}> | |
| {LANGUAGES.map(lang => { | |
| const activeLangs = surveyData?.languages?.map(l => (l.language?.code || l.code || '').toLowerCase()) || []; | |
| const isConfiguredInFormbricks = !surveyData || activeLangs.some(code => | |
| code === lang.locale.toLowerCase() || | |
| code === lang.code.toLowerCase() || | |
| code.startsWith(lang.code.toLowerCase()) || | |
| lang.locale.toLowerCase().startsWith(code) | |
| ); | |
| return ( | |
| <label | |
| key={lang.locale} | |
| style={{ | |
| display: 'flex', | |
| alignItems: 'center', | |
| justifyContent: 'space-between', | |
| padding: '0.75rem', | |
| background: selectedLocales.includes(lang.locale) ? 'rgba(59, 130, 246, 0.1)' : 'rgba(255, 255, 255, 0.05)', | |
| border: `1px solid ${selectedLocales.includes(lang.locale) ? 'rgba(59, 130, 246, 0.5)' : 'transparent'}`, | |
| borderRadius: '8px', | |
| cursor: 'pointer', | |
| opacity: isConfiguredInFormbricks ? 1 : 0.65, | |
| transition: 'all 0.2s' | |
| }} | |
| > | |
| <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}> | |
| <input | |
| type="checkbox" | |
| checked={selectedLocales.includes(lang.locale)} | |
| onChange={() => toggleLocale(lang.locale)} | |
| style={{ width: '16px', height: '16px' }} | |
| /> | |
| <span style={{ fontSize: '0.875rem' }}>{lang.name} <strong>({lang.locale})</strong></span> | |
| </div> | |
| {surveyData && ( | |
| <span style={{ | |
| fontSize: '0.7rem', | |
| padding: '0.15rem 0.4rem', | |
| borderRadius: '4px', | |
| background: isConfiguredInFormbricks ? 'rgba(16, 185, 129, 0.15)' : 'rgba(245, 158, 11, 0.15)', | |
| color: isConfiguredInFormbricks ? '#10b981' : '#f59e0b' | |
| }}> | |
| {isConfiguredInFormbricks ? 'Configured' : 'Not in FB'} | |
| </span> | |
| )} | |
| </label> | |
| ); | |
| })} | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| ); | |
| } | |