Write a vscode plug-in to help read the code of I18N project

Time:2022-1-2

Write a vscode plug-in to help read the code of I18N project

Write a vscode plug-in to help read the code of I18N project

introduce

The project the author is currently involved in is for global users. The project has to be internationalized, even if it is just a simple projectOK buttonofOK copywritingIt has to be translated into the languages of different countries, so we can’t directly name it in the codeokInstead, it may be nameduser_base_plan_edit_ok_buttonThis kind of name, and in order to distinguishi18nSimilar to other naming methods, our team will use all uppercaseUSER_BASE_PLAN_EDIT_OK_BUTTON, and reading more such code will makeDry eyes, similar to the pseudo code in the following figure:

Write a vscode plug-in to help read the code of I18N project

To solve this problemBad readingMy expected effect is that when the mouse hovers over the target text, a pop-up box will appear, and the pop-up box should at least tell me the Chinese or English meaning of the word. The effect is as follows:

Write a vscode plug-in to help read the code of I18N project

It can be seen that if this plug-in is done well, it may not only be used ini18nThis is just a point. It can be used in many aspects, such as a code103993283The specific meaning of this code can be displayed as a plug-in.

1: Initialize vscode project

Students who have not done vscode plug-in are recommended to read the introductory tutorial I wrote first:

The plug-in I made this time is aimed at my current project and has no extensive application ability, so it was not released to the official vscode. After development, it was packaged and sent to the company’s intranet and group.

Create project: the project name here is tentatively calledi18n2c

   yo code

Write a vscode plug-in to help read the code of I18N project

2: Initialize schema

     extension.jsClean up the documents:

const vscode = require("vscode");

function activate(context) {
  vscode. window. Showinformationmessage ("I18N translation plug-in loading completed");
}

module.exports = {
  activate,
};

Modificationpackage.jsonFile: set to start loading our plug-ins when the resources are loaded

{
// ...

  "activationEvents": [
    "onStartupFinished"
  ],

// ...
}

Clickf5Start the debugging mode, and the following figure shows that the plug-in can be started normally:
Write a vscode plug-in to help read the code of I18N project

3: Initialize hover file

We puthoverThe following logic is placed in SRC:

Write a vscode plug-in to help read the code of I18N project

Make a simple transformationextension.js, add the hover method:

const vscode = require("vscode");
const hover = require("./src/hover");

function activate(context) {
  vscode. window. Showinformationmessage ("I18N translation plug-in loading completed");

  context.subscriptions.push(hover);
}

module.exports = {
  activate,
};

     hover.jsExport handling method when hovering

const vscode = require("vscode");

module.exports = vscode.languages.registerHoverProvider("*", {
  provideHover(document, position) {
    return new vscode. Hover (` I18N plug-in comes to help you get through the robbery ';
  },
});

When you hover in any position, the effect is as follows:

Write a vscode plug-in to help read the code of I18N project

4: Recognition of I18N target copy

The technical schemes of each team are different. Here I only design the scheme of our team, hoping to attract jade by throwing bricks:

Our teamI18N copywritingAre capitalized and useUnderlineLinked to each other, and I found that the global exceptI18N copywritingThere are no more than three characters in the stringUnderline, andI18N copywritingAt least fourUnderlineTherefore, at present, I use to judge whether the string contains more than three characters'_'

const vscode = require("vscode");

module.exports = vscode.languages.registerHoverProvider("*", {
  provideHover(document, position) {
    const word = document.getText(document.getWordRangeAtPosition(position));

    if (word.split("_").length > 3) {
      return new vscode. Hover (` I18N plug-in comes to help you get through the robbery ';
    }

  },
});

abovewordThat’s what we gotHovered text

5: How to translate into Chinese

We found it up thereTo be translatedHere we will study how to translate this copy. Generally, there will be a translation dictionary package for I18N, one of which is our teamJSON file, the difference is that each key is lowercase. The general appearance is as follows:

Write a vscode plug-in to help read the code of I18N project

All I have to do is read this file andTo be translatedConvert your copy to lowercase and match it again.

const vscode = require("vscode");
const fs = require("fs");

module.exports = vscode.languages.registerHoverProvider("*", {
  provideHover(document, position) {
    const word = document.getText(document.getWordRangeAtPosition(position));

    let jsonCN = JSON.parse(
      fs.readFileSync("/xxxx/xxxxx/langs/zh-CN.json")
    );

    if (word.split("_").length > 3) {
      return new vscode. Hover (` I18N plug-in comes to help you through the robbery:
-Chinese: ${jsoncn [word. Tolocalelovercase()]}
      `);
    }

  },
});

Write a vscode plug-in to help read the code of I18N project

OursI18N dictionaryThey are all placed in the same folder, so I only need to know this folder. By default, take out the Chinese and English copy in it and transform it.

const vscode = require("vscode");
const fs = require("fs");

module.exports = vscode.languages.registerHoverProvider("*", {
  provideHover(document, position) {
    const word = document.getText(document.getWordRangeAtPosition(position));

    if (word.split("_").length > 3) {
      const i18nPath = "/xxxx/xxxxx/langs";
      const jsonUrlCN = i18nPath + "/zh-CN.json";
      const jsonUrlEN = i18nPath + "/en.json";
      let jsonCN = JSON.parse(fs.readFileSync(jsonUrlCN));
      let jsonEN = JSON.parse(fs.readFileSync(jsonUrlEN));
      return new vscode. Hover (` I18N plug-in comes to help you through the robbery:
-Chinese: ${jsoncn [word. Tolocalelovercase()]}
-English: ${jsonen [word. Tolocalelovercase()]}
      `);
    }
  },
});

Write a vscode plug-in to help read the code of I18N project

therei18nPathOf course, it can be configured by users. Next, we’ll study it.

6: Setting configuration

The location of our translation dictionary file must not beWrite deadIn plug-ins, users often need to set their own settings. At this time, we need the concept of vscode setting, as shown in the following figure:

Write a vscode plug-in to help read the code of I18N project

Step 1: initialize configuration items

We comepackage.jsonFile addsettingConfiguration item:

{
  "contributes": {
    "configuration": {
      "type": "object",
      "Title": "I18N translation configuration",
      "properties": {
        "vscodePluginI18n.i18nPath": {
          "type": "string",
          "default": "",
          "Description": "location of translation file"
        },
        "vscodePluginI18n.open": {
          "type": "boolean",
          "default": true,
          "Description": "turning on 18N translation"
        }
      }
    }
  },
}

typeSet toBooleanAutomatically generatedCheckBoxIt’s quite convenient.

Step 2: initial plug-in reading configuration

extension.jsFile:

const vscode = require("vscode");

function activate(context) {
  const i18nPath = vscode.workspace
    .getConfiguration()
    .get("vscodePluginI18n.i18nPath");
  const open = vscode.workspace.getConfiguration().get("vscodePluginI18n.open");

  if (open && i18nPath) {
    vscode. window. Showinformationmessage ("I18N translation plug-in in place");
    const hover = require("./src/hover");
    context.subscriptions.push(hover);
  }
}

module.exports = {
  activate,
};

Note here that ifconst hover = require("./src/hover");If it is written at the top, the hovering translation effect may not be closed. There is a pit in this. We will talk about it in detail later.

Step 3: read the path when hovering

hover.jsFile:

const vscode = require("vscode");
const fs = require("fs");

module.exports = vscode.languages.registerHoverProvider("*", {
  provideHover(document, position) {
    const i18nPath = vscode.workspace
      .getConfiguration()
      .get("vscodePluginI18n.i18nPath");
    const open = vscode.workspace
      .getConfiguration()
      .get("vscodePluginI18n.open");

    if (i18nPath && open) {
      const word = document.getText(document.getWordRangeAtPosition(position));

      if (word.split("_").length > 3) {
        const i18nPath = "/xxxxx/xxxx/langs";
        const jsonUrlCN = i18nPath + "/zh-CN.json";
        const jsonUrlEN = i18nPath + "/en.json";
        let jsonCN = JSON.parse(fs.readFileSync(jsonUrlCN));
        let jsonEN = JSON.parse(fs.readFileSync(jsonUrlEN));
        return new vscode. Hover (` I18N plug-in comes to help you through the robbery:
-Chinese: ${jsoncn [word. Tolocalelovercase()]}
-English: ${jsonen [word. Tolocalelovercase()]}
      `);
      }
    }
  },
});

7: When to determine whether to open the plug-in

If inextension.jsThe document introduceshoverModule, even if we judge that the user is not enabledI18N translationThe process will also go to the hover module, but if we are judging whether the user is enabled or notI18N translationImport afterhoverThe module will cause that if the user changes the configuration and starts to translate, he can’t respond in time. The user needs to restart, so we need to decide how to design here.

8: Prompt pop-up

If the user turns onI18N translationHowever, if the path is not configured, we can actually display a pop-up box to prompt the user whether to fill in the path of the translation dictionary, similar to the effect shown in the following figure:

Write a vscode plug-in to help read the code of I18N project

extension.jsUsed in the fileshowInformationMessageThis method, but add two parameters:

const vscode = require("vscode");

function activate(context) {
  const i18nPath = vscode.workspace
    .getConfiguration()
    .get("vscodePluginI18n.i18nPath");
  const open = vscode.workspace.getConfiguration().get("vscodePluginI18n.open");

  if (open && i18nPath) {
    vscode. window. Showinformationmessage ("I18N translation plug-in in place");
    const hover = require("./src/hover");
    context.subscriptions.push(hover);
  } else if (open && !i18nPath) {
    vscode.window
      "Yes", "message show", "translate file"
      .then((result) => {
           If (result = = = "yes"){

           }
      });
  }
}

module.exports = {
  activate,
};

9: Select file

When the user clicks “yes”, we need to use the API provided by vscode to select the file, and get the return value of the file for active setting:

vscode.window.showOpenDialogMethod, it has four main parameters:

  1. canSelectFilesOptional file
  2. canSelectFoldersOptional folder
  3. canSelectManyCan I select more than one
  4. openLabelPrompt copy
  5. The return value is the array. The path attribute of the first element is the global path of the file

Write a vscode plug-in to help read the code of I18N project

Finally reuseupdateMethod to actively update the global configuration.

vscode.window
      "Yes", "message show", "translate file"
      .then((result) => {
        If (result = = = "yes"){
          vscode.window
            .showOpenDialog({
              Canselectfiles: false, // optional files
              Canselectfolders: true, // is a folder optional
              Canselectmany: false, // can multiple be selected
              Openlabel: "please select a translation folder",
            })
            .then(function (res) {
              vscode.workspace
                .getConfiguration()
                .update("vscodePluginI18n.i18nPath", res[0].path, true);
            });
        }
      });
  }

end

This is it. I hope to make progress with you.