Skip to content

Commit

Permalink
refactor code & fix bugs
Browse files Browse the repository at this point in the history
fix #3
fix #4
  • Loading branch information
pizzacat83 committed Jan 28, 2017
1 parent f5420c1 commit 383b568
Showing 1 changed file with 157 additions and 109 deletions.
266 changes: 157 additions & 109 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,130 +5,178 @@ import * as vscode from 'vscode';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

var request=require("request-promise");
var nullsignal = "<null>";
var Cases:{[index:string]:{applyfunc:(string,boolean)=>string, sample:string}}={
"PascalCase": {
"applyfunc": (word:string, isFirst:boolean)=>{return word[0].toUpperCase()+word.slice(1);},
"sample": "Aa"
},
"camelCase": {
"applyfunc": (word:string, isFirst:boolean)=>{return isFirst?word:(word[0].toUpperCase()+word.slice(1));},
"sample": "aA"
},
"snake_case": {
"applyfunc": (word:string, isFirst:boolean)=>{return isFirst?word:"_"+word;},
"sample": "a_a"
},
"SNAKE_CASE": {
"applyfunc": (word:string, isFirst:boolean)=>{return (isFirst?word:"_"+word).toUpperCase();},
"sample": "A_A",
},
"hy-phen-a-tion": {
"applyfunc": (word:string, isFirst:boolean)=>{return isFirst?word:"-"+word;},
"sample": "a-a"
},
"no case": {
"applyfunc": (word:string, isFirst:boolean)=>{return isFirst?word:" "+word;},
"sample": "a a"
}
}
class CodicExtension{

// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "codic" is now active!');
protected context:vscode.ExtensionContext;
protected request=require('request-promise');
protected nullsymbol:string="<null>";
protected cases:{[index:string]:{applyfunc:(string,boolean)=>string, sample:string}}={
"PascalCase": {
"applyfunc": (word:string, isFirst:boolean)=>{return word[0].toUpperCase()+word.slice(1);},
"sample": "Aa"
},
"camelCase": {
"applyfunc": (word:string, isFirst:boolean)=>{return isFirst?word:(word[0].toUpperCase()+word.slice(1));},
"sample": "aA"
},
"snake_case": {
"applyfunc": (word:string, isFirst:boolean)=>{return isFirst?word:"_"+word;},
"sample": "a_a"
},
"SNAKE_CASE": {
"applyfunc": (word:string, isFirst:boolean)=>{return (isFirst?word:"_"+word).toUpperCase();},
"sample": "A_A",
},
"hy-phen-a-tion": {
"applyfunc": (word:string, isFirst:boolean)=>{return isFirst?word:"-"+word;},
"sample": "a-a"
},
"no case": {
"applyfunc": (word:string, isFirst:boolean)=>{return isFirst?word:" "+word;},
"sample": "a a"
}
};

// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable:vscode.Disposable[] = [];
disposable.push(vscode.commands.registerCommand('extension.codicTranslate', () => {
var ACCESS_TOKEN=vscode.workspace.getConfiguration('codic').get('ACCESS_TOKEN');
// The code you place here will be executed every time your command is executed
if(context.globalState.get("codic.case")===undefined && context.workspaceState.get("codic.case")===undefined){
vscode.window.showErrorMessage("case が設定されていません。")
}
vscode.window.showInputBox({prompt: 'Input a Japanese phrase'})
.then(function(input){
if(input === undefined || input === ""){
return Promise.reject(undefined);
} else {
var options = {
uri : 'https://api.codic.jp/v1/engine/translate.json',
method:'GET',
qs:{text:input},
headers: {'Authorization': 'Bearer '+ ACCESS_TOKEN},
transform2xxonly: true,
transform: function(body){return JSON.parse(body);},
};
return request(options);

}
}).then(function(body){
if(!body)return Promise.reject(undefined);
var candidates: Array<Array<string>> = [];
for(var i = 0; i < body[0].words.length; i++){
var temp: Array<string> = [];
for(var j = 0; j < body[0].words[i]['candidates'].length; j++){
temp.push(body[0].words[i]['candidates'][j]['text']===null?nullsignal:body[0].words[i]['candidates'][j]['text']);
}
candidates.push(temp);
}
return candidates;
}).then(function(candidates:Array<Array<string>>){
var p :Promise<any>=Promise.resolve();
var isFirst=true;
candidates.forEach(function(words){
p=p.then(function(){return vscode.window.showQuickPick(words)})
.then(function(choice){
// {#BUG}: QuickPick loop continues when the user focus out
// {#TODO}: catch the reject() below
if(!choice){
return Promise.reject(undefined);
}
if(choice === nullsignal){
return Promise.resolve(undefined);
}
var editor = vscode.window.activeTextEditor;
var edit = new vscode.WorkspaceEdit();
var case_ = context.workspaceState.get<string>("codic.case");
case_=case_===undefined?context.globalState.get<string>("codic.case"):case_;
edit.insert(editor.document.uri, editor.selection.anchor, Cases[case_]["applyfunc"](choice,isFirst));
isFirst=false;
return vscode.workspace.applyEdit(edit);
})
.then(function(){
var editor = vscode.window.activeTextEditor;
editor.selection = new vscode.Selection(editor.selection.end,editor.selection.end);
});
});
});
}));

disposable.push(vscode.commands.registerCommand("extension.codicSetLocalCase", ()=>{
constructor(context:vscode.ExtensionContext){
this.context=context;
}

public translate():void{
this.getInputText()
.then((input:string) => this.sendRequest(input, this.getAccessToken()))
.then((body)=>this.listCandidates(body))
.then((candidates)=>this.pickCandidates(candidates))
}

public setLocalCase(){
var keys=[];
for(var key in Cases){
for(var key in this.cases){
keys.push(key);
}
vscode.window.showQuickPick(keys)
.then(function(choice){context.workspaceState.update("codic.case", choice);});
}))
.then((choice) => {this.context.workspaceState.update("codic.case", choice);});
}

disposable.push(vscode.commands.registerCommand("extension.codicSetGlobalCase", ()=>{
public setGlobalCase(){
var keys=[];
for(var key in Cases){
for(var key in this.cases){
keys.push(key);
}
vscode.window.showQuickPick(keys)
.then(function(choice){context.globalState.update("codic.case", choice);});
}))
.then((choice) => {this.context.globalState.update("codic.case", choice);});
}

public dispose(){

}

protected getAccessToken():string{
let ACCESS_TOKEN=vscode.workspace.getConfiguration('codic').get<string>('ACCESS_TOKEN');
if(ACCESS_TOKEN===undefined){
vscode.window.showErrorMessage("case が設定されていません。");
throw 'no ACCESS_TOKEN';
}
return ACCESS_TOKEN;
}

protected getInputText():PromiseLike<string|boolean>{
return vscode.window.showInputBox({prompt: 'Input a Japanese phrase'})
.then((input) => {
if(input === undefined || input === ""){
return Promise.reject(undefined);
}
return input;
});
}

protected sendRequest(text:string,ACCESS_TOKEN:string){
let options = {
uri : 'https://api.codic.jp/v1/engine/translate.json',
method:'GET',
qs:{text:text},
headers: {'Authorization': 'Bearer '+ ACCESS_TOKEN},
transform2xxonly: true,
transform: (body) => {return JSON.parse(body);},
};
return this.request(options);
}

protected listCandidates(body):string[][]{
let candidates: string[][] = [];
for(let i = 0; i < body[0].words.length; i++){
let temp: Array<string> = [];
for(let j = 0; j < body[0].words[i]['candidates'].length; j++){
temp.push(body[0].words[i]['candidates'][j]['text']===null?this.nullsymbol:body[0].words[i]['candidates'][j]['text']);
}
if(temp.length===0){temp = [body[0].words[i]['text']];}
candidates.push(temp);
}
return candidates;
}

protected getCase(){
let case_ = this.context.workspaceState.get<string>("codic.case");
case_=case_===undefined?this.context.globalState.get<string>("codic.case"):case_;
return case_;
}

protected applyCase(text:string, isFirst:boolean, case_:string){
return this.cases[case_]["applyfunc"](text,isFirst);
}

protected pickCandidates(candidates:string[][]):Promise<any>{
let p:Promise<any> = Promise.resolve();
let isFirst = true;
candidates.forEach((words) => {
p=p.then(() => {return vscode.window.showQuickPick(words)})
.then((choice) => {
if(choice === undefined) return Promise.reject("user focused out");
if(choice === this.nullsymbol){
return Promise.resolve(null);
}
return this.insertText(this.applyCase(choice,isFirst,this.getCase()));
})
.then((val)=>{if(val!==null){isFirst = false;}})
.then(this.moveCursorToEndOfSelection);
});
return p;
}

protected insertText(text:string){
let editor = vscode.window.activeTextEditor;
let edit = new vscode.WorkspaceEdit();
edit.insert(editor.document.uri, editor.selection.anchor, text);
return vscode.workspace.applyEdit(edit);
}

protected moveCursorToEndOfSelection(){
let editor = vscode.window.activeTextEditor;
editor.selection = new vscode.Selection(editor.selection.end,editor.selection.end);
}

}

export function activate(context: vscode.ExtensionContext) {

// Use the console to output diagnostic information (console.log) and errors (console.error)

// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json

let codicExtension = new CodicExtension(context);
let disposable:vscode.Disposable[] = [];
disposable.push(vscode.commands.registerCommand('extension.codicTranslate', () => {codicExtension.translate();}));

disposable.push(vscode.commands.registerCommand("extension.codicSetLocalCase", () => {codicExtension.setLocalCase();}));

disposable.push(vscode.commands.registerCommand("extension.codicSetGlobalCase", () => {codicExtension.setGlobalCase();}));

disposable.forEach(function(item){
context.subscriptions.push(codicExtension);
disposable.forEach((item) => {
context.subscriptions.push(item);
});
context.subscriptions.push(request);
}

// this method is called when your extension is deactivated
Expand Down

0 comments on commit 383b568

Please # to comment.