Skip to content

Commit

Permalink
Merge pull request #21 from yanxiaodi/task-4
Browse files Browse the repository at this point in the history
Add select-hover-translation
  • Loading branch information
yanxiaodi authored May 9, 2022
2 parents 2441e2a + d77882d commit 447835c
Show file tree
Hide file tree
Showing 14 changed files with 467 additions and 271 deletions.
24 changes: 13 additions & 11 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false, // set this to true to hide the "out" folder with the compiled JS files
"dist": false // set this to true to hide the "dist" folder with the compiled JS files
},
"search.exclude": {
"out": true, // set this to false to include "out" folder in search results
"dist": true // set this to false to include "dist" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
}
"files.exclude": {
"out": false, // set this to true to hide the "out" folder with the compiled JS files
"dist": false // set this to true to hide the "dist" folder with the compiled JS files
},
"search.exclude": {
"out": true, // set this to false to include "out" folder in search results
"dist": true // set this to false to include "dist" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off",
"commentTranslate.multiLineMerge": true,
"commentTranslate.hover.enabled": true
}
17 changes: 13 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
# Change Log

All notable changes to the "translator-helper" extension will be documented in this file.
## [0.3.0] - 2022-05-09

Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
- Automatically copy the translated text to clipboard for the `translate` command.
- Support selection hover translation. You can select a word or a sentence, then you will see a popup with the translated text. Click **Copy** to copy the translated text. You can turn off this feature in the settings.

## [Unreleased]
## [0.2.0] - 2022-05-08

- Initial release
- Update dependencies.

## [0.1.0]

- Add reverse translation.

## [0.0.3]

- Initial release.
35 changes: 16 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,30 @@

Google translate API supported. For Chinese users, you can update the settings to use GoogleCN service.

* Translate: <kbd>Ctrl</kbd>+<kbd>T</kbd>. Select a word or a sentence, then press Ctrl+T. The translated text will be shown on the status bar. Click the text, it will be copied to the clipboard.
- Translate and Insert. <kbd>Alt</kbd>+<kbd>T</kbd>. It is very useful when you localize the docs. Click any position in the paragraph, then press Alt+T. The whole paragraph will be translated then inserted after the original text.

![Translate](images/sample1.gif)
![Translate and Insert](images/sample2.gif)

* Translate and Insert. <kbd>Alt</kbd>+<kbd>T</kbd>. It is very useful when you localize the docs. Click any position in the paragraph, then press Alt+T. The whole paragraph will be translated then inserted after the original text.
- Reverse Translate and Insert: <kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>T</kbd>. Translate the text from the _target_ language to the _source_ language.

![Translate and Insert](images/sample2.gif)
- Select and Hover Translate. You can select a word or a sentence, hover the mouse over the text, then the text will be translated in a popup. You can click **Copy** to copy the translated text.

![Selection and Hover Translation](images/sample3.gif)

- Translate: <kbd>Ctrl</kbd>+<kbd>T</kbd>. Select a word or a sentence, then press Ctrl+T. The translated text will be shown on the status bar. The text will be automatically copied to the clipboard.

* Reverse Translate and Insert: <kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>T</kbd>. Translate the text from the *target* language to the *source* language.
![Translate](images/sample1.gif)

## Extension Settings

You can change the User Settings to specify the API and the languages you need to translate.

This extension contributes the following settings:

* `translatorHelper.api`: Specify the translate API. Options: `google`, `google-cn`.
* `translatorHelper.sourceLanguage`: The source language code. The default value is `en`.
* `translatorHelper.targetLanguage`: The target language code. The default value is `zh-CN`.
- `translatorHelper.api`: Specify the translate API. Options: `google`, `google-cn`.
- `translatorHelper.sourceLanguage`: The source language code. The default value is `en`.
- `translatorHelper.targetLanguage`: The target language code. The default value is `zh-CN`.
- `translatorHelper.enableSelectionHoverTranslation`: Whether to enable selection and hover translation. The default value is `true`.

The source and target languages are identified using the [iso-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) codes. For example, the source language is English (en) and the target language is Chinese-Simplified (zh-CN). You can find all the supported languages here: [Language support](https://cloud.google.com/translate/docs/languages)

Expand All @@ -39,20 +44,12 @@ The source and target languages are identified using the [iso-639-1](https://en.

The keybinding might not work properly on some linux machines. Please open issues to describe your environment. Thanks.

## Release Notes

### 0.1.0

Add reverse translation.

### 0.0.3

Initial release.
## Release Note

-----------------------------------------------------------------------------------------------------------
Please see [Changelog](CHANGELOG.md)

### For more information

* [GitHub Repository](https://github.com/yanxiaodi/vscode-translator-helper)
- [GitHub Repository](https://github.com/yanxiaodi/vscode-translator-helper)

**Enjoy!**
Binary file added images/sample3.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 15 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "translator-helper",
"displayName": "Translator Helper",
"description": "A tool to improve the efficiency of the translation, especially for the localization of Docs.",
"version": "0.2.0",
"version": "0.3.0",
"publisher": "XiaodiYan",
"repository": "https://github.com/yanxiaodi/vscode-translator-helper",
"engines": {
Expand All @@ -11,6 +11,14 @@
"categories": [
"Other"
],
"keywords": [
"translate",
"translator",
"translation",
"google translate",
"interpret",
"翻译"
],
"badges": [{
"url": "https://dev.azure.com/xiaodiyan/VSCode%20TranslatorHelper/_apis/build/status/yanxiaodi.vscode-translator-helper?branchName=master",
"href": "https://dev.azure.com/xiaodiyan/VSCode%20TranslatorHelper/_build?definitionId=58",
Expand All @@ -34,9 +42,7 @@
],
"icon": "images/icon.png",
"activationEvents": [
"onCommand:translatorHelper.translateInsert",
"onCommand:translatorHelper.reverseTranslateInsert",
"onCommand:translatorHelper.translate"
"*"
],
"main": "./dist/extension.js",
"contributes": {
Expand Down Expand Up @@ -94,6 +100,11 @@
"type": "string",
"default": "zh-CN",
"description": "The target language."
},
"translatorHelper.enableSelectionHoverTranslation": {
"type": "boolean",
"default": true,
"description": "Enable the hover translation when the selection is not empty."
}
}
}
Expand Down
121 changes: 121 additions & 0 deletions src/commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { getContent } from './store';
import { CommandIds } from './consts';
import { ITranslatorService } from './translate-service';
import {
getParagraph,
getSelectionText,
insertText,
setCurrentEditor,
} from './doc-service';
import { commands, env, ExtensionContext, StatusBarItem, window } from 'vscode';

export const regiserCommands = (
context: ExtensionContext,
servie: ITranslatorService,
source: string,
target: string,
statusBarItem: StatusBarItem
) => {
let translateInsert = commands.registerCommand(
CommandIds.translateInsertCommand,
async () => await translateInsertCommand(servie, source, target)
);
let reverseTranslateInsert = commands.registerCommand(
CommandIds.reverseTranslateInsertCommand,
async () => await reverseTranslateInsertCommand(servie, source, target)
);

let translate = commands.registerCommand(
CommandIds.translateCommand,
async () => await translateCommand(servie, source, target, statusBarItem)
);

let copyTranslationText = commands.registerCommand(
CommandIds.copyTranslationTextCommand,
copyTranslationTextCommand
);
context.subscriptions.push(
translateInsert,
reverseTranslateInsert,
translate,
copyTranslationText
);
};

export const translateInsertCommand = async (
translatorService: ITranslatorService,
source: string,
target: string
) => {
// The code you place here will be executed every time your command is executed
setCurrentEditor();
const text = getParagraph();
try {
if (text.trim() !== '') {
let result = await translatorService.translate(text, source, target);
insertText(result);
}
} catch (error: any) {
window.showErrorMessage(`Error occurs. ${error}`);
}
};

export const reverseTranslateInsertCommand = async (
translatorService: ITranslatorService,
source: string,
target: string
) => {
// The code you place here will be executed every time your command is executed
setCurrentEditor();
const text = getParagraph();
try {
if (text.trim() !== '') {
let result = await translatorService.translate(text, target, source);
insertText(result);
}
} catch (error: any) {
window.showErrorMessage(`Error occurs. ${error}`);
}
};

export const translateCommand = async (
translatorService: ITranslatorService,
source: string,
target: string,
statusBarItem: StatusBarItem
) => {
// The code you place here will be executed every time your command is executed
setCurrentEditor();
const text = getSelectionText();
try {
if (text.trim() !== '') {
const result = await translatorService.translate(text, source, target);
statusBarItem.hide();
statusBarItem.text = `$(book) ${result}`;
statusBarItem.show();
// Copy to clipboard
copyToClipboard(result);
} else {
statusBarItem.hide();
}
} catch (error: any) {
window.showErrorMessage(`Error occurs. ${error}`);
}

// Display a message box to the user
//vscode.window.showInformationMessage('Hello World!');
};

export const copyTranslationTextCommand = () => {
try {
var content = getContent();
copyToClipboard(content);
} catch (error: any) {
window.showErrorMessage(`Error occurs. ${error}`);
}
};

const copyToClipboard = (content: string) => {
env.clipboard.writeText(content);
window.showInformationMessage(`Translation text copyied to the clipboard!`);
};
21 changes: 21 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { workspace } from 'vscode';

export const getConfiguration = <T>(key: string) => {
return workspace.getConfiguration('translatorHelper').get<T>(key);
};

export const getApiConfiguration = () => {
return getConfiguration<string>('api') ?? 'google';
};

export const getSourceLanguageConfiguration = () => {
return getConfiguration<string>('sourceLanguage') ?? 'en';
};

export const getTargetLanguageConfiguration = () => {
return getConfiguration<string>('targetLanguage') ?? 'zh-CN';
};

export const getEnableSelectionHoverTranslationConfiguration = () => {
return getConfiguration<boolean>('enableSelectionHoverTranslation') ?? true;
};
6 changes: 6 additions & 0 deletions src/consts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export enum CommandIds {
translateInsertCommand = 'translatorHelper.translateInsert',
reverseTranslateInsertCommand = 'translatorHelper.reverseTranslateInsert',
translateCommand = 'translatorHelper.translate',
copyTranslationTextCommand = 'translatorHelper.copyTranslationText',
}
67 changes: 67 additions & 0 deletions src/doc-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Position, Selection, TextEditor, window } from 'vscode';

let editor: TextEditor | undefined;

export const setCurrentEditor = () => {
editor = window.activeTextEditor;
};

export const getParagraph = (): string => {
if (editor !== undefined) {
let startLine = editor.selection.start.line;
let endLine = editor.selection.end.line;
const endCharacter = editor.document.lineAt(endLine).text.length;
editor.selection = new Selection(startLine, 0, startLine, endCharacter);
var paragraph = editor.selection;
let result = editor.document.getText(paragraph);
if (result !== undefined) {
return result;
} else {
return '';
}
} else {
return '';
}
};

export const getSelectionText = (): string => {
if (editor !== undefined) {
return editor.document.getText(editor.selection);
} else {
return '';
}
};

export const insertText = (text: string): void => {
if (editor !== undefined) {
let end = editor.selection.end;
editor
.edit((editBuilder) => {
editBuilder.insert(end, '\n');
editBuilder.insert(end, text);
})
.then((success) => {
if (success && editor !== undefined) {
let end = editor.selection.end;
editor.selection = new Selection(end, end);
let startLine = editor.selection.start.line;
let endLine = editor.selection.end.line;
const endCharacter = editor.document.lineAt(endLine).text.length;
editor.selection = new Selection(
startLine,
0,
startLine,
endCharacter
);
}
});
}
};

export const isHoverOnSelection = (position: Position): boolean => {
return (
editor !== undefined &&
!editor.selection.isEmpty &&
editor.selection.contains(position)
);
};
Loading

0 comments on commit 447835c

Please sign in to comment.