rob-revisited/ide/ui/js/translations.js

503 lines
29 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The Translations window: the project's catalogues as a grid of keys × languages (Symfony translations/<domain>.<locale>.*,
// JumPHP config/lang.yaml, Laravel lang/). A cell is edited in place (Enter writes that file's line only); missing cells are red,
// texts left the same as the source are yellow, placeholder / ICU / HTML problems orange; the code scan marks keys found
// nowhere and lists keys the code uses that no catalogue has. A key added goes into every language file of its domain (the
// missing files made), renamed in every file and in the templates / PHP (diffs first), deleted everywhere. AI translation
// (Claude, OpenCode or a chat server, as the resource editors' Generate…) fills missing cells as proposals, accepted per cell
// or all at once; the glossary (.jumphp/translations-glossary.json) goes with each request. The PHP side: ide/src/Translations.
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t, dialog, prompt, confirm, menu, copyText } from './ui.js';
import { ChangesView, symfonyStyles, fileLink } from './symfony-events.js';
const MAX_ROWS = 400;
const LANG_NAMES = { fr: 'Français', en: 'English', es: 'Español', de: 'Deutsch', it: 'Italiano', pt: 'Português', nl: 'Nederlands', pl: 'Polski', ru: 'Русский', uk: 'Українська', tr: 'Türkçe', ja: '日本語', zh: '中文', ko: '한국어' };
function styles() {
symfonyStyles();
if (document.getElementById('translations-css')) return;
document.head.append(el('link', { id: 'translations-css', rel: 'stylesheet', href: new URL('../css/translations.css', import.meta.url).href }));
}
/** the issues of a cell as words for its tooltip */
function issueText(issues) {
return (issues || []).map((i) => i === 'missing' ? t('Missing') : i === 'identical' ? t('Same text as the source language') : i).join('\n');
}
export class TranslationsPanel {
constructor(app) {
this.app = app;
this.node = el('div.tr-view');
this.data = null;
this.groupId = prefs.get('trGroup', '');
this.filter = prefs.get('trFilter', 'all');
this.search = '';
this.limit = MAX_ROWS;
this.scanned = false;
this.proposals = {}; // group id => key => locale => {text, issues}
this.debugMissing = []; // from debug:translation
this.busy = '';
this.editing = null; // {key, locale}
this.changes = new ChangesView(app, 'translations.apply', () => this.load());
styles();
this.render();
}
title() { return t('Translations'); }
actions() {
return [
el('button', { title: t('Scan the code: keys used, unused, missing'), onclick: () => this.load(true) }, icon('eye')),
el('button', { title: t('Refresh'), onclick: () => this.load() }, icon('refresh')),
];
}
shown() { if (!this.data && !this.busy) this.load(); }
get group() { return this.data?.groups.find((g) => g.id === this.groupId) || this.data?.groups[0] || null; }
async load(scan = false) {
this.busy = scan ? t('Scanning the code…') : t('Reading the catalogues…');
this.render();
try {
this.data = await backend.invoke('translations.list', { usages: scan || this.scanned, rescan: scan });
if (scan) this.scanned = true;
if (!this.data.groups.some((g) => g.id === this.groupId)) this.groupId = this.data.groups[0]?.id || '';
} catch (e) { notify(e.message, 'error', { title: t('Translations') }); }
this.busy = '';
this.render();
}
// --------------------------------------------------------------------------------------------- rows
proposalsOf(g) { return this.proposals[g.id] || {}; }
rows(g) {
const q = this.search.trim().toLowerCase();
const props = this.proposalsOf(g);
const f = this.filter;
return g.keys.filter((k) => {
const checks = g.checks[k] || {};
if (q && !k.toLowerCase().includes(q) && !Object.values(g.values[k] || {}).some((v) => (v || '').toLowerCase().includes(q))) return false;
if (f === 'all') return true;
if (f === 'missing') return Object.values(checks).some((i) => i.includes('missing'));
if (f.startsWith('missing:')) return (checks[f.slice(8)] || []).includes('missing');
if (f === 'identical') return Object.values(checks).some((i) => i.includes('identical'));
if (f === 'problems') return Object.values(checks).some((i) => i.some((x) => x !== 'missing' && x !== 'identical'));
if (f === 'unused') return g.usage && g.usage[k] === 'unused';
if (f === 'proposals') return !!props[k];
return true;
});
}
stats(g) {
let missing = 0; let problems = 0;
for (const k of g.keys) for (const issues of Object.values(g.checks[k] || {})) {
if (issues.includes('missing')) missing++;
if (issues.some((x) => x !== 'missing' && x !== 'identical')) problems++;
}
return { missing, problems };
}
// --------------------------------------------------------------------------------------------- render
render() {
clear(this.node);
if (!this.data) {
this.node.append(el('div.sx-empty', {}, this.busy || t('Reading the catalogues…')));
return;
}
const g = this.group;
const bar = el('div.tr-bar');
if (!g) {
this.node.append(el('div.sx-empty', {}, t('No translation catalogue in this project (translations/*.yaml, config/lang.yaml, lang/).')),
el('div.tr-bar', {}, el('button.btn', { onclick: () => this.addLanguage() }, icon('plus'), t('Add a language…'))));
return;
}
const select = el('select.input.small', { title: t('Translation domain'), onchange: () => { this.groupId = select.value; prefs.set('trGroup', select.value); this.limit = MAX_ROWS; this.render(); } },
...this.data.groups.map((x) => el('option', { value: x.id, selected: x.id === g.id }, `${x.label} (${x.keys.length})`)));
const search = el('input.input.small.tr-search', { type: 'search', placeholder: t('Search in keys and texts'), value: this.search,
oninput: () => { this.search = search.value; this.limit = MAX_ROWS; this.renderGrid(); } });
const filters = [['all', t('All keys')], ['missing', t('Missing translations')], ...g.locales.map((l) => [`missing:${l}`, t('Missing in {lang}', { lang: l })]),
['identical', t('Same as the source')], ['problems', t('Placeholder / ICU problems')], ['unused', t('Not found in the code')], ['proposals', t('AI proposals')]];
const filter = el('select.input.small', { title: t('Filter'), onchange: () => { this.filter = filter.value; prefs.set('trFilter', filter.value); this.limit = MAX_ROWS; this.renderGrid(); } },
...filters.map(([v, label]) => el('option', { value: v, selected: v === this.filter }, label)));
const s = this.stats(g);
bar.append(...[select, search, filter,
el('button.btn.small', { title: t('Add a key in every language'), onclick: () => this.addKey() }, icon('plus'), t('Key')),
el('button.btn.small', { title: t('Add a language: its files in every domain'), onclick: () => this.addLanguage() }, icon('globe'), t('Language')),
el('button.btn.small', { title: t('Translate with AI (Claude / OpenCode)'), onclick: () => this.aiDialog() }, icon('claude'), t('Translate…')),
g.kind === 'jumphp' ? el('button.btn.small', { title: t('The 14 languages of JumPHP: add the missing ones and translate them'), onclick: () => this.fill14() }, t('Fill the 14 languages')) : null,
el('button.btn.small', { title: t('Terms never translated, or always translated the same way'), onclick: () => this.glossaryDialog() }, icon('book'), t('Glossary')),
this.app.project.capabilities?.console === 'bin/console' ? el('button.btn.small', { title: t('Ask Symfony which keys a language lacks (debug:translation)'), onclick: () => this.debugTranslation() }, icon('console'), 'debug:translation') : null].filter(Boolean));
this.node.append(bar);
this.node.append(el('div.tr-summary', {},
el('span', {}, t('{n} keys', { n: g.keys.length })), ' · ',
el('span', {}, t('{n} languages', { n: g.locales.length })), ' · ',
el('span.tr-c-missing', {}, t('{n} missing', { n: s.missing })), ' · ',
el('span.tr-c-problem', {}, t('{n} problems', { n: s.problems })),
g.locales.length ? el('span.sx-muted', {}, ' · ' + t('source: {lang}', { lang: g.source })) : null,
this.busy ? el('span.tr-busy', {}, ' ' + this.busy) : null,
Object.keys(g.errors || {}).length ? el('div.tr-errors', {}, ...Object.entries(g.errors).map(([p, e]) => el('div', {}, icon('warning'), ` ${p}: ${e}`))) : null));
this.node.append(this.changes.node);
const props = this.proposalsOf(g);
const nProps = Object.values(props).reduce((n, byL) => n + Object.keys(byL).length, 0);
if (nProps) {
this.node.append(el('div.tr-proposals', {}, icon('claude'), ' ', t('{n} AI proposals: check them in the grid', { n: nProps }),
el('button.btn.small.primary', { onclick: () => this.accept(null) }, t('Accept all')),
el('button.btn.small', { onclick: () => { delete this.proposals[g.id]; this.render(); } }, t('Discard all'))));
}
const missing = [...(this.data.missing || []), ...this.debugMissing.filter((m) => !(this.data.missing || []).some((x) => x.key === m.key))];
if (missing.length) this.node.append(this.missingBox(missing));
this.grid = el('div.tr-grid');
this.node.append(this.grid);
this.renderGrid();
}
missingBox(missing) {
const open = prefs.get('trMissingOpen', true);
const box = el('details.tr-missing', { open, ontoggle: () => prefs.set('trMissingOpen', box.open) },
el('summary', {}, t('{n} keys used in the code but in no catalogue', { n: missing.length })),
...missing.slice(0, 200).map((m) => el('div.tr-missing-row', {},
el('code', {}, m.key), m.domain ? el('span.sx-badge', {}, m.domain) : null,
...(m.places || []).slice(0, 2).map((p) => fileLink(this.app, p.path, p.line, `${p.path}:${p.line}`)),
el('button.btn.small', { onclick: () => this.addKey(m.key, m.domain) }, icon('plus'), t('Add')))));
return box;
}
renderGrid() {
const g = this.group;
if (!this.grid || !g) return;
clear(this.grid);
const rows = this.rows(g);
const props = this.proposalsOf(g);
const table = el('table.tr-table');
table.append(el('thead', {}, el('tr', {}, el('th.tr-key', {}, t('Key')),
...g.locales.map((l) => el('th', { title: (LANG_NAMES[l] ? LANG_NAMES[l] + '\n' : '') + (g.files[l] || t('no file yet: made when a text is written')) }, l, l === g.source ? el('span.sx-badge', {}, t('source')) : null,
g.files[l] ? null : el('span.sx-badge.red', {}, t('no file')))), el('th.tr-act'))));
const body = el('tbody');
for (const k of rows.slice(0, this.limit)) {
const tr = el('tr');
const usage = g.usage?.[k];
tr.append(el('td.tr-key', { title: k + (g.notes?.[k] ? '\n' + g.notes[k] : ''), oncontextmenu: (e) => { e.preventDefault(); this.rowMenu(k, e); } },
el('span.tr-keytext', {}, k),
usage === 'unused' ? el('span.sx-badge.red', { title: t('Found nowhere in the code or the templates') }, t('unused')) : null,
usage === 'maybe' ? el('span.sx-badge', { title: t('Only as a plain text of the code (not a translation call)') }, '?') : null));
for (const l of g.locales) tr.append(this.cell(g, k, l, props[k]?.[l]));
tr.append(el('td.tr-act', {}, el('button.sx-icon', { title: t('More'), onclick: (e) => this.rowMenu(k, e) }, icon('more'))));
body.append(tr);
}
table.append(body);
this.grid.append(table);
if (!rows.length) this.grid.append(el('div.sx-empty', {}, t('Nothing to show with this filter.')));
if (rows.length > this.limit) this.grid.append(el('button.btn.small.tr-more', { onclick: () => { this.limit += MAX_ROWS; this.renderGrid(); } }, t('Show {n} more', { n: Math.min(MAX_ROWS, rows.length - this.limit) })));
}
cell(g, k, l, proposal) {
const v = g.values[k]?.[l];
const issues = g.checks[k]?.[l] || [];
const cls = ['td.tr-cell'];
if (issues.includes('missing')) cls.push('missing');
else if (issues.includes('identical')) cls.push('identical');
if (issues.some((x) => x !== 'missing' && x !== 'identical')) cls.push('problem');
if (proposal) cls.push('proposal');
const td = el(cls.join('.'), { title: [v ?? '', issueText(issues)].filter(Boolean).join('\n\n'), ondblclick: () => this.edit(td, k, l), onclick: (e) => { if (e.detail === 1 && !proposal) this.edit(td, k, l); } });
if (proposal) {
td.title = t('AI proposal') + ':\n' + proposal.text + (proposal.issues.length ? '\n\n' + proposal.issues.join('\n') : '');
td.append(el('div.tr-proposal-text' + (proposal.issues.length ? '.bad' : ''), {}, proposal.text),
el('div.tr-proposal-act', {},
el('button.sx-icon', { title: t('Accept'), onclick: (e) => { e.stopPropagation(); this.accept([[k, l]]); } }, icon('check')),
el('button.sx-icon', { title: t('Edit'), onclick: (e) => { e.stopPropagation(); this.edit(td, k, l, proposal.text); } }, icon('edit')),
el('button.sx-icon', { title: t('Discard'), onclick: (e) => { e.stopPropagation(); delete this.proposals[g.id][k][l]; if (!Object.keys(this.proposals[g.id][k]).length) delete this.proposals[g.id][k]; this.render(); } }, icon('close'))));
} else {
td.append(el('span.tr-text', {}, v ?? ''));
}
return td;
}
edit(td, k, l, initial) {
if (this.editing) return;
const g = this.group;
this.editing = { k, l };
const before = g.values[k]?.[l] ?? '';
const area = el('textarea.input.tr-edit', { rows: Math.min(6, Math.max(1, String(initial ?? before).split('\n').length)) });
area.value = initial ?? before;
clear(td);
td.append(area);
area.focus();
area.select();
let done = false;
const finish = async (save) => {
if (done) return;
done = true;
this.editing = null;
if (save && (area.value !== before || initial !== undefined)) await this.write(g, [{ op: 'set', key: k, locale: l, value: area.value }], [[k, l]]);
else this.renderGrid();
};
area.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); finish(true); }
else if (e.key === 'Escape') { e.preventDefault(); finish(false); }
});
area.addEventListener('blur', () => finish(true));
}
/** edits written at once (cells, keys added / deleted); the proposals of the cells written go away */
async write(g, ops, cells = []) {
try {
await backend.invoke('translations.edit', { group: g.id, ops, apply: true });
for (const [k, l] of cells) {
if (this.proposals[g.id]?.[k]) { delete this.proposals[g.id][k][l]; if (!Object.keys(this.proposals[g.id][k]).length) delete this.proposals[g.id][k]; }
}
this.app.editors.reloadFromDisk?.();
this.app.tree?.refresh?.();
await this.load();
} catch (e) { notify(e.message, 'error', { title: t('Translations') }); this.renderGrid(); }
}
async accept(cells) {
const g = this.group;
const props = this.proposalsOf(g);
cells ??= Object.entries(props).flatMap(([k, byL]) => Object.keys(byL).map((l) => [k, l]));
if (!cells.length) return;
await this.write(g, cells.map(([k, l]) => ({ op: 'set', key: k, locale: l, value: props[k][l].text })), cells);
notify(t('{n} translations written', { n: cells.length }), 'success', { title: t('Translations') });
}
// --------------------------------------------------------------------------------------------- keys
rowMenu(k, e) {
const g = this.group;
menu([
{ label: t('Rename…'), action: () => this.rename(k) },
{ label: t('Delete…'), action: () => this.remove(k) },
{ label: t('Translate this key with AI…'), action: () => this.aiDialog([k]) },
{ label: t('Where is it used?'), action: () => this.places(k) },
{ label: t('Copy the key'), action: () => copyText(k) },
...g.locales.filter((l) => g.files[l]).map((l) => ({ label: t('Open {file}', { file: g.files[l] }), action: () => this.openAt(g.files[l], k) })),
], e.type === 'click' && e.currentTarget instanceof Element ? e.currentTarget : { x: e.clientX, y: e.clientY });
}
async openAt(path, key) {
await this.app.editors.open(path).catch((err) => notify(err.message, 'error'));
// the key's line: its last word in the file (nested YAML writes only the last segment)
try {
const text = await backend.invoke('file.read', { path }).then((r) => (typeof r === 'string' ? r : r.content || ''));
const word = key.includes('.') && /\.ya?ml$/.test(path) ? key.split('.').pop() : key;
const line = text.split('\n').findIndex((x) => x.includes(word)) + 1;
if (line > 0) this.app.editors.open(path, { line }).catch(() => null);
} catch { /* the file is open: enough */ }
}
async places(k) {
const list = await backend.invoke('translations.places', { key: k }).catch((e) => { notify(e.message, 'error'); return []; });
dialog({ title: t('Where is {key} used?', { key: k }), body: el('div.tr-places', {}, list.length ? list.map((p) => el('div', {}, fileLink(this.app, p.path, p.line, `${p.path}:${p.line}`)))
: el('p.sx-muted', {}, t('Found nowhere in the code or the templates'))), buttons: [{ label: t('Close') }] });
}
addKey(key = '', domain = null) {
let g = this.group;
if (domain) g = this.data.groups.find((x) => x.domain === domain && x.kind === 'symfony') || g;
const name = el('input.input', { value: key, placeholder: g.kind === 'jumphp' ? 'NEW GAME' : 'app.menu.home' });
const inputs = Object.fromEntries(g.locales.map((l) => [l, el('textarea.input', { rows: 1, placeholder: l === g.source ? (g.kind === 'jumphp' ? '' : t('the text')) : t('empty: to translate') })]));
if (g.kind !== 'jumphp' && key && inputs[g.source]) inputs[g.source].value = '';
dialog({
title: t('New key in {domain}', { domain: g.label }),
body: el('div.sx-form', {}, el('label', {}, t('Key')), name,
...g.locales.flatMap((l) => [el('label', {}, l + (g.files[l] ? '' : ' *')), inputs[l]]),
el('div.sx-full.sx-muted', {}, t('The key goes into the file of every language (* : the file is made).'))),
buttons: [{ label: t('Cancel') }, { label: t('Add'), primary: true, action: async () => {
const k = name.value.trim();
if (!k) { notify(t('Give the key a name'), 'warning'); return false; }
await this.write(g, [{ op: 'add', key: k, values: Object.fromEntries(g.locales.map((l) => [l, inputs[l].value])) }]);
this.data.missing = (this.data.missing || []).filter((m) => m.key !== k);
this.debugMissing = this.debugMissing.filter((m) => m.key !== k);
this.render();
} }],
});
}
async rename(k) {
const g = this.group;
const code = el('input', { type: 'checkbox', checked: true });
const name = el('input.input', { value: k });
dialog({
title: t('Rename {key}', { key: k }),
body: el('div', {}, name, el('label.tr-check', {}, code, ' ', t('Also in the templates and the PHP code that use it'))),
buttons: [{ label: t('Cancel') }, { label: t('Preview'), primary: true, action: async () => {
const to = name.value.trim();
if (!to || to === k) return false;
const r = await backend.invoke('translations.rename', { group: g.id, key: k, to, code: code.checked });
if (!r.changes.length) { notify(t('Nothing to change'), 'info'); return; }
this.changes.show(r.changes);
} }],
});
setTimeout(() => name.select(), 20);
}
async remove(k) {
const g = this.group;
const files = g.locales.filter((l) => g.values[k]?.[l] !== null && g.files[l]).map((l) => g.files[l]);
const usage = g.usage?.[k];
const ok = await confirm(t('Delete {key}?', { key: k }), t('From {files}.', { files: [...new Set(files)].join(', ') }) + (usage === 'used' ? ' ' + t('The code still uses it.') : ''), { ok: t('Delete'), danger: true });
if (ok) await this.write(g, [{ op: 'delete', key: k }]);
}
async addLanguage(preset = '') {
const code = el('input.input', { value: preset, placeholder: 'de, pt_BR, zh_Hans…' });
const fill = el('select.input', {}, el('option', { value: 'empty' }, t('Empty (to translate)')), el('option', { value: 'source' }, t('The source text')), el('option', { value: 'todo' }, 'TODO'));
dialog({
title: t('Add a language'),
body: el('div.sx-form', {}, el('label', {}, t('Language code')), code, el('label', {}, t('Texts')), fill,
el('div.sx-full.sx-muted', {}, t('Its file is made in every translation domain, with every key.'))),
buttons: [{ label: t('Cancel') }, { label: t('Preview'), primary: true, action: async () => {
const r = await backend.invoke('translations.addLanguage', { locale: code.value.trim(), fill: fill.value });
if (!r.changes.length) { notify(t('Nothing to change'), 'info'); return; }
this.changes.show(r.changes);
} }],
});
}
// --------------------------------------------------------------------------------------------- AI
async aiDialog(keys = null, presetTargets = null) {
const g = this.group;
const providers = (await backend.invoke('ai.providers').catch(() => [{ id: 'claude', name: 'Claude', kind: 'claude' }]))
.filter((p) => ['claude', 'opencode', 'chat'].includes(p.kind));
const sources = g.kind === 'jumphp' ? ['en', ...g.locales.filter((l) => l !== 'en')] : g.locales;
const from = el('select.input.small', {}, ...sources.map((l) => el('option', { value: l, selected: l === g.source }, l === 'en' && g.kind === 'jumphp' ? t('en (the keys)') : l)));
const targets = (presetTargets || g.locales.filter((l) => l !== g.source));
const boxes = Object.fromEntries(g.locales.filter((l) => !(g.kind !== 'jumphp' && l === g.source)).map((l) => [l, el('input', { type: 'checkbox', checked: targets.includes(l) })]));
const scope = el('select.input.small', {},
el('option', { value: 'missing' }, t('Missing translations only')),
el('option', { value: 'filtered' }, t('The rows shown ({n})', { n: this.rows(g).length })),
el('option', { value: 'all' }, t('Every key (replaces the texts)')));
const provider = el('select.input.small', {}, ...providers.map((p) => el('option', { value: p.id }, p.name)));
provider.value = prefs.get('trAiProvider', providers[0]?.id || 'claude');
const model = el('input.input.small', { placeholder: t('model (optional): sonnet, haiku, opus…'), value: prefs.get('trAiModel:' + provider.value, '') });
const estimate = el('p.sx-muted');
const plan = () => {
const f = from.value;
const out = [];
for (const [l, box] of Object.entries(boxes)) {
if (!box.checked || l === f) continue;
const ks = (keys || (scope.value === 'filtered' ? this.rows(g) : g.keys)).filter((k) => {
const src = g.values[k]?.[f] || (g.kind === 'jumphp' && f === 'en' ? k : '');
if (!src) return false;
return keys || scope.value !== 'missing' || (g.checks[k]?.[l] || []).includes('missing');
});
if (ks.length) out.push([l, ks]);
}
return out;
};
const update = () => {
const p = plan();
const n = p.reduce((s, [, ks]) => s + ks.length, 0);
const chars = p.reduce((s, [, ks]) => s + ks.reduce((c, k) => c + (g.values[k]?.[from.value] || k).length + k.length, 0), 0);
const batches = p.reduce((s, [, ks]) => s + Math.ceil(ks.length / 40), 0);
estimate.textContent = t('{n} texts, {chars} characters, {batches} requests to the AI', { n, chars, batches });
};
for (const x of [from, scope, ...Object.values(boxes)]) x.addEventListener('change', update);
provider.addEventListener('change', () => { model.value = prefs.get('trAiModel:' + provider.value, ''); });
update();
dialog({
title: t('Translate with AI'),
wide: true,
body: el('div.sx-form', {},
el('label', {}, t('From')), from,
el('label', {}, t('To')), el('div.tr-langs', {}, ...Object.entries(boxes).map(([l, b]) => el('label.tr-check', {}, b, ' ', l))),
keys ? null : el('label', {}, t('What')), keys ? null : scope,
el('label', {}, t('With')), provider,
el('label', {}, t('Model')), model,
el('div.sx-full', {}, estimate),
el('div.sx-full.sx-muted', {}, t('The proposals show in the grid first: nothing is written until you accept them. The glossary goes with each request.'))),
buttons: [{ label: t('Cancel') }, { label: t('Translate'), primary: true, action: async () => {
prefs.set('trAiProvider', provider.value);
prefs.set('trAiModel:' + provider.value, model.value.trim());
this.runAi(g, from.value, plan(), provider.value, model.value.trim());
} }],
});
}
async runAi(g, from, plan, provider, model) {
if (!plan.length) { notify(t('Nothing to translate'), 'info'); return; }
const p = (this.proposals[g.id] ??= {});
const extra = provider === 'claude' || provider === 'opencode' ? {} : { key: prefs.get('aiKey:' + provider, ''), baseUrl: prefs.get('aiBase:' + provider, '') };
let count = 0;
const errors = [];
for (const [l, keys] of plan) {
this.busy = t('AI: translating {n} texts to {lang}…', { n: keys.length, lang: l });
this.render();
try {
const r = await backend.invoke('translations.ai', { group: g.id, from, to: l, keys, provider, model, ...extra });
for (const x of r.results) { (p[x.key] ??= {})[l] = { text: x.text, issues: x.issues }; count++; }
errors.push(...r.errors);
} catch (e) { errors.push(`${l}: ${e.message}`); }
}
this.busy = '';
if (count && this.filter !== 'all') this.filter = 'proposals';
this.render();
if (errors.length) notify(errors.join('\n'), 'warning', { title: t('Translate with AI') });
notify(t('{n} AI proposals: check them in the grid', { n: count }), count ? 'success' : 'info', { title: t('Translate with AI') });
}
/** JumPHP: the 14 languages of the engine in config/lang.yaml, then the AI for what they lack */
async fill14() {
const g = this.group;
const lacking = (this.data.languages || []).filter((l) => l !== 'en' && !g.locales.includes(l));
if (lacking.length) {
const ok = await confirm(t('Fill the 14 languages'), t('Add {langs} to {file}, then translate what is missing with AI?', { langs: lacking.join(', '), file: g.files[g.locales[0]] || 'config/lang.yaml' }), { ok: t('Add') });
if (!ok) return;
try {
await backend.invoke('translations.edit', { group: g.id, ops: lacking.map((l) => ({ op: 'addLocale', locale: l, fill: 'empty' })), apply: true });
this.app.editors.reloadFromDisk?.();
await this.load();
} catch (e) { notify(e.message, 'error'); return; }
}
this.aiDialog(null, (this.data.languages || []).filter((l) => l !== 'en'));
}
// --------------------------------------------------------------------------------------------- glossary, Symfony
async glossaryDialog() {
const g = this.group;
const terms = (this.data.glossary?.terms || []).map((x) => ({ ...x }));
const list = el('div.tr-glossary');
const draw = () => {
clear(list);
list.append(el('div.tr-gl-row.head', {}, el('span', {}, t('Term')), el('span', {}, t('Never translate')), el('span', {}, t('Fixed translations (fr=…, de=…)')), el('span', {}, t('Note')), el('span')));
terms.forEach((x, i) => {
const fixed = el('input.input.small', { value: Object.entries(x.translations || {}).map(([l, v]) => `${l}=${v}`).join(', '), placeholder: g.locales.filter((l) => l !== g.source).slice(0, 2).map((l) => `${l}=…`).join(', ') });
fixed.addEventListener('change', () => { x.translations = Object.fromEntries(fixed.value.split(',').map((s) => s.split('=').map((y) => y.trim())).filter(([l, v]) => l && v)); });
list.append(el('div.tr-gl-row', {},
el('input.input.small', { value: x.term || '', oninput: (e) => { x.term = e.target.value; } }),
el('input', { type: 'checkbox', checked: !!x.keep, onchange: (e) => { x.keep = e.target.checked; } }),
fixed,
el('input.input.small', { value: x.note || '', oninput: (e) => { x.note = e.target.value; } }),
el('button.sx-icon', { title: t('Remove'), onclick: () => { terms.splice(i, 1); draw(); } }, icon('trash'))));
});
list.append(el('button.btn.small', { onclick: () => { terms.push({ term: '', keep: false, translations: {}, note: '' }); draw(); } }, icon('plus'), t('Term')));
};
draw();
dialog({
title: t('Glossary'), wide: true,
body: el('div', {}, el('p.sx-muted', {}, t('Kept in {file} (shared with git). Only the terms a text contains go with an AI request.', { file: this.data.glossary?.path || '.jumphp/translations-glossary.json' })), list),
buttons: [{ label: t('Cancel') }, { label: t('Save'), primary: true, action: async () => {
this.data.glossary = await backend.invoke('translations.glossary', { terms });
} }],
});
}
async debugTranslation() {
const g = this.group;
const locale = await prompt(t('debug:translation: which language?'), { value: g.locales.find((l) => l !== g.source) || g.source });
if (!locale) return;
this.busy = t('Asking Symfony…');
this.render();
try {
const r = await backend.invoke('translations.debug', { locale: locale.trim() });
this.debugMissing = r.missing.map((m) => ({ key: m.key, domain: m.domain, places: [] }));
if (!r.missing.length) notify(r.code === 0 ? t('Symfony finds nothing missing in {lang}.', { lang: locale }) : r.output.slice(-600), r.code === 0 ? 'success' : 'warning', { title: 'debug:translation' });
} catch (e) { notify(e.message, 'error', { title: 'debug:translation' }); }
this.busy = '';
this.render();
}
}