Use message translator for widget copy

This commit is contained in:
rajchales-monito
2026-07-30 08:43:38 +02:00
parent 16329a1681
commit 7eb81e2e22
+10 -30
View File
@@ -1191,32 +1191,17 @@ async function translateWidgetCopyOnce(sourceCopy, sourceLanguage, targetLanguag
const settings = getTranslationSettings();
if (!settings.enabled || !settings.openaiApiKey || !targetLanguage || sourceLanguage === targetLanguage) return null;
try {
const response = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
"Authorization": `Bearer ${settings.openaiApiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: settings.model,
input: [
{
role: "system",
content: "Translate UI copy for a live chat widget. Return only compact JSON with the same keys. Preserve brand names and meaning. Keep labels short."
},
{
role: "user",
content: JSON.stringify({ sourceLanguage, targetLanguage, copy: sourceCopy })
}
]
})
});
if (!response.ok) {
const openAiError = await openAiErrorFromResponse(response);
throw new Error(openAiError.message);
const translatedCopy = {};
for (const field of WIDGET_COPY_FIELDS) {
const value = String(sourceCopy[field] || "").trim();
if (!value) {
translatedCopy[field] = "";
continue;
}
const result = await translateText(value, targetLanguage, settings.model, settings.openaiApiKey);
translatedCopy[field] = String(result.translatedText || value).trim();
}
const data = await response.json();
const translated = normalizeWidgetCopyEntry(parseJsonBlock(outputTextFromResponse(data)), targetLanguage);
const translated = normalizeWidgetCopyEntry(translatedCopy, targetLanguage);
if (widgetCopyLooksUntranslated(sourceCopy, translated)) return null;
return translated;
} catch (error) {
@@ -1230,11 +1215,6 @@ function widgetCopyLooksUntranslated(sourceCopy, translatedCopy) {
return importantFields.every((field) => String(sourceCopy[field] || "").trim() === String(translatedCopy[field] || "").trim());
}
function parseJsonBlock(value) {
const text = String(value || "").trim().replace(/^```(?:json)?/i, "").replace(/```$/, "").trim();
return JSON.parse(text);
}
function syncLegacyWidgetCopy(settings) {
for (const language of Object.keys(settings.widgetCopy || {})) {
const copy = settings.widgetCopy[language];