Text Editor - Translate Plugin
Translate selected text to another language using an external API.
#Usage
import { TextEditor } from '@primeui/vue-texteditor';
import { translatePlugin } from './translate-plugin';<TextEditor.Root v-model="value" :plugins="[[translatePlugin, { source: 'en', target: 'fr' }]]">
<TextEditor.Toolbar>
<TranslateButton />
</TextEditor.Toolbar>
<TextEditor.Content />
</TextEditor.Root>The Translate plugin adds a translate command that replaces the selected text with its translation from an external service. Pass the plugin as a [plugin, options] tuple to set the source and target languages, then call pluginCommands.translate?.translate() from a widget.
#Overview
The plugin translates through the MyMemory Translation API. Source and target language codes are passed as plugin options and can be overridden per call.
#Plugin Definition
import { defineTextEditorPlugin } from '@primeui/vue-texteditor';
export interface TranslateOptions {
source?: string;
target?: string;
}
export const translatePlugin = defineTextEditorPlugin<TranslateOptions>('translate', ({ getSelectedText, replaceSelection, options }) => {
const source = options?.source ?? 'en';
const target = options?.target ?? 'fr';
return {
commands: {
translate: async (sourceLang?: unknown, targetLang?: unknown) => {
const text = getSelectedText();
if (!text) return;
const from = (sourceLang as string) ?? source;
const to = (targetLang as string) ?? target;
const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=${from}|${to}`;
const response = await fetch(url);
const data = await response.json();
if (data.responseStatus === 429 || data.quotaFinished) {
replaceSelection('Translation rate limit reached for this demo. Please try again later.');
return;
}
const translated = data.responseData?.translatedText;
if (translated) {
replaceSelection(translated);
}
}
}
};
});#Options
| Option | Type | Default | Description |
|---|---|---|---|
source | string | 'en' | Source language code (e.g. en, fr) |
target | string | 'fr' | Default target language code |
#Commands
| Command | Signature | Description |
|---|---|---|
translate | (sourceLang?: string, targetLang?: string) => Promise<void> | Translates selected text from source to target language |
#Example
Select text, pick a target language, click Translate.
The demo runs on the MyMemory free tier (1000 words/day) and caps selections at 10 words.
Loading Demo...