A vscode plug-in, they help you work efficiently, and I only care if you eat on time

Time:2021-7-4

A vscode plug-in, they help you work efficiently, and I only care if you eat on time

Remind-me

In order to prevent the world from being destroyed, to protect the peace of the world, to maintain the power to fight with PM, and to maintain the health of excellent programmers who love their work and forget to eat like me, I would like to present the sand sculpture I just madevscodeplug-in unit:Remind-me。 The main functions are: remind you to eat and work, use and weatherAPIGet the current weather, rain warning, don’t forget to bring an umbrella and show the temperature curve in the next 12 hours.

ctrl+shift+, One click to open sand sculpture life

They help you work efficiently, but I only care if you eat on time

They help you work efficiently, but I only care if you are eating on time. —— shehuiwang. google translate


Features

Remind you to eat and get off work, and look at the weather

Remind you to do something, eat or get off work, etc. Show current weather and temperature curve


Quick start:

Configuration item

Name | Description | Default

Remind-me.defaultcity | city name, supporting Pinyin and Chinese (recommended) | Nanjing
Remind-me.hefengappkey | and wind weather key (free), 5000 times a day to call | “
Remind-me.lunchtime | dinner time | 11:30
Remind-me.getofftime | off hours | 18:00

The windy weather API provides 5000 queries per day,estimateIt’s not enough..

Shortcut keyctrl+shift+,See if it rains

Enjoy!


development process

before:

  • vscode
  • node.js
  • npm
  • Weather dataAPI
  • generator-code
  • yo

npm i -g yo generator-code

process

Start:

yo code
  • Select JavaScript or typescript, fill in the project name, project description, publisher (I have applied and configured it, but you didn’t have it when initializing), and whether to initialize git warehouse

A vscode plug-in, they help you work efficiently, and I only care if you eat on time

  • Generate directory after initialization
├─ .vscode
├─ node_ Modules # dependent folder
├ - Test # test
│  .eslintrc.json
│  .gitattributes
│  .gitignore
│  .vscodeignore
Change log.md change log
│ extension.js # entry
│ jsconfig.json # JS configuration file
│  package-lock.json
Project configuration file
│  README.md
└─ vsc-extension-quickstart.md
  • Our main focus is on the entry fileextension.jsAnd project profilespackage.jsonIn fact,
// package.json
{
    "name": "remind-me",
    "displayName": "remind-me",
    "description": "remind you do sth",
    "version": "0.0.1",
    "publisher": "shehuiwang", 
    "engines": {
        "vscode": "^1.25.0"
    },
    "Categories": [// categories
        "Other"
    ],
    "Activationevents": [// trigger conditions
        "onCommand:extension.sayHello"
    ],
    "Main": "." / extension ", // entry file
    "contributes": {
        "Commands": [// corresponding command
            {
                "command": "extension.sayHello",
                "title": "Hello World"
            }
        ]
    },
    "scripts": {
        "postinstall": "node ./node_modules/vscode/bin/install",
        "test": "node ./node_modules/vscode/bin/test"
    },
    "devDependencies": {
        "typescript": "^2.6.1",
        "vscode": "^1.1.6",
        "eslint": "^4.11.0",
        "@types/node": "^7.0.43",
        "@types/mocha": "^2.2.42"
    }
}
// extension.js
const vscode = require('vscode');
function activate(context) {
    //The commands in package. JSON are defined here
    let disposable = vscode.commands.registerCommand('extension.sayHello', function () {
       vscode.window.showInformationMessage('Hello World!');  //  Popup Message 
    });
    context.subscriptions.push(disposable); //  subscribe
}
exports.activate = activate; //  This method is executed when the plug-in is activated
function deactivate() {
}
exports.deactivate = deactivate; //  Execute this method when the plug-in is disabled

debug

PressF5Will pop up withExtended development hostNew window of the logo,ctrl+shift+pInput in the pop-up input boxHello worldEnter to see the notification message.

  • Our target function

    • Obtain urban weather information;
    • Bad weather warning;
    • Display the temperature curve;
    • Time and pop up reminder;
    • Automatic start;

code

configuration file

// package.json
{
  "name": "remind-me",
  "DisplayName": "dinner",
  "description": "Remind you to do something, lunch or get off work, etc.",
  "version": "1.0.1",
  "publisher": "shehuiwang",
  "license": "MIT",
  "icon": "icon.png",
  "engines": {
    "vscode": "^1.25.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/kelrvins/remind-me"
  },
  "categories": [
    "Other"
  ],
  "keywords": [
      "remind",
      "get off work",
      "lunch"
  ],
  "activationEvents": [
    "*" // it is said that this configuration can be automatically turned on after vscode is started, but I tried to lower the trigger probability, and I didn't find a solution, < del > try again later < / del >
  ],
  "main": "./extension",
  "contributes": {
    "Commands": [// command of Ctrl + Shift + P pop-up box
      {
        "command": "extension.remindMe",
        "title": "remind me"
      }
    ],
    "Configuration": {// configuration item in settings
      "type": "object",
      "title": "remind me configuration",
      "properties": {
        "remind-me.defaultCity": {
          "type": "string",
          "Default": "Nanjing",
          "Description": "set default city (eg.nanjing or Nanjing)"
        },
        "remind-me.hefengAppkey": {
          "type": "string",
          "default": "",
          "description": "You can get your private key from here: https://wx.jdcloud.com/market/datas/26/10610"
        },
        "remind-me.lunchTime": {
          "type": "string",
          "default": "11:30",
          "description": "set lunch times"
        },
        "remind-me.getOffTime": {
          "type": "string",
          "default": "18:00",
          "description": "set get off work time times"
        }
      }
    },
    "keybindings": [
      {
        "command": "extension.remindMe",
        "key": "ctrl+shift+,",
        "mac": "ctrl+shift+,"
      }
    ]
  },
  "scripts": {
    "postinstall": "node ./node_modules/vscode/bin/install",
    "test": "node ./node_modules/vscode/bin/test"
  },
  "dependencies": {
    "web-request": "^1.0.7"
  },
  "devDependencies": {
    "@types/mocha": "^2.2.42",
    "@types/node": "^7.0.43",
    "eslint": "^4.11.0",
    "typescript": "^2.6.1",
    "vscode": "^1.1.6"
  }
}

Body code

Registration instructionsextension.remindMe, and start the timer, every 60 seconds, to remind the time, do not know if there are other good solutions, the garbage code Porter can not think of it.

// extension.js

function activate(context) {
  let cityApi = vscode.commands.registerCommand('extension.remindMe', function() {
      const config = vscode.workspace.getConfiguration('remind-me')
      const reg = new RegExp(/^([01][0-9]|2[0-3]):([0-5][0-9])$/)
      const addZero1 = (num, len = 2) => `0${num}`.slice(-len)
      if ((config.lunchTime && reg.test(config.lunchTime))||(config.getOffTime && reg.test(config.getOffTime))) {   
        if (timer) clearInterval(timer)
        timer = setInterval(function() {
          const configTime = vscode.workspace.getConfiguration('remind-me')
          const [lh, lm] = configTime.lunchTime.split(':')
          const [gh, gm] = configTime.getOffTime.split(':')
          if ( lh && lm &&
            addZero1(new Date().getHours()) == lh &&
            addZero1(new Date().getMinutes()) == lm) {
            getWeatherInfo(configTime.defaultCity,1)
          }
          if (gh && gm &&
            addZero1(new Date().getHours()) == gh &&
            addZero1(new Date().getMinutes()) == gm) {
            getWeatherInfo(configTime.defaultCity,2)
          }
        }, 60000) // once a minute, not on the hour, so the time may not be accurate. Should we consider reminding one minute in advance
      }
      If (config. Defaultcity) {// there is a default value in the configuration item
        getWeatherInfo(config.defaultCity)
      }There is no default value in the else {// configuration item
        const options = {
          ignoreFocusOut: true,
          password: false,
          Prompt: 'please input you city (eg.beijing or Beijing), it's better to fill in the configuration file'
        }
        vscode.window.showInputBox(options).then(value => {
          if (!value) {
            vscode.window.showInformationMessage('please input you city')
            return
          }
          const cityName = value.trim()
          getWeatherInfo(cityName)
        })
      }
    }
  )
  context.subscriptions.push(cityApi)
}

Get city weather

WebRequest.get(`https://way.jd.com/he/freeweather?city=${encodeURI(cityName)}&appkey=${appkey}`).then(reps => {})

I used to use itaxiosDo the network request, development preview no problem, but after packaging as VISX installation promptcommand extension.remindMe not foundIn order to solve this problem, it took just an hour. Later, by checking the developer tools, we found that the root cause wasCannot find module "axios"After half an hour, I couldn’t find a solution, so I went to other open source plug-ins to look at the code and found that they were usingWebRequestA handful of bitter tears.

Draw temperature curve

The temperature data with 3-hour intervals is provided for windy weather, and the temperature curve is displayed by character splicing

A vscode plug-in, they help you work efficiently, and I only care if you eat on time

/**
// extension.js

 *Draw temperature curve
 *@ param {array} ParM weather array
 */
function renderTmpLine(parm) {
  let array = []
  let weatherNotice = ''
  parm.forEach(el => {
    if (el.cond.code > 204 && !weatherNotice) {
      weatherNotice = ` , ${el.date.substr(8, 2) - new Date().getDate() > 0 ? ' Tomorrow ':'today'} ${el. Date. Substr (- 5, 2)} there is ${el. Cond. TXT} after o'clock`
    }
    array.push(el.tmp)
  })
  const tmpSigns = ['__ ', '▁▁ ', '▂  ', '▃ ', '▅  ', '▆  ', '▇  ']
  const tmpRange = {
    max: Math.max.apply(Math, array),
    min: Math.min.apply(Math, array)
  }
  let tmpLine = ''
  array.forEach(el => {
    tmpLine += tmpSigns[el - tmpRange.min > 6 ? 6 : el - tmpRange.min]
  })
  Return (tmpline + weathernotice + ', maximum:' + tmprange. MAX + ' ° C. Minimum: '+ tmprange. Min +' ° C')
}

Get city weather

/**
 *Get city weather
 *@ param {string} cityname city name
 *Lunch and off-duty signs in @ param {string} operation
 */
function getWeatherInfo(cityName,operation=0) {
  Const config = vscode. Workspace. Getconfiguration ('remind me ') // get the data in the configurable item
  const appkey = config.hefengAppkey
    ? config.hefengAppkey
    : 'YOUR_ Key '// here is the key of mild weather
  WebRequest.get(`https://way.jd.com/he/freeweather?city=${encodeURI(cityName)}&appkey=${appkey}`).
  then(reps => {
    let rep = JSON.parse(reps.body)
    if (rep.code != 10000) {
      vscode.window.showInformationMessage('sorry please try again')
      return
    }
    const weatherData = rep.result.HeWeather5[0]
    if (weatherData.status !== 'ok') {
      vscode.window.showInformationMessage(`sorry,${weatherData.status}`)
      return
    }
    const tmpLine = renderTmpLine(weatherData.hourly_forecast)
    Vscode. Window. Showinformationmessage (` temperature curve in the next 12 hours: ${tmpline} '))
    const isRain =
      weatherData.hourly_forecast[0].cond.code >= 300 &&
      weatherData.hourly_forecast[0].cond.code < 500
    vscode.window.showInformationMessage(
      `${weatherData.basic.city}, ${weatherData.now.cond.txt}, ${weatherData.now.tmp} ° C. Next two hours ${WeatherData. Hourly_ forecast[0].cond.txt}${isRain ? ' , Please bring rain gear,
      ...[isRain ? '  Oh, oh ':']  
    )//... ['ooh '] add this when it rains. Just add a button and the pop-up window won't disappear automatically. It's so sweet of me to be a product manager if I can't get along with it in the future
    if(operation==1){
      Vscode. Window. Showinformationmessage
    }
    if(operation==2){
      Vscode.window.showinformationmessage
    }
  })
}

publish

preparation

A vscode plug-in, they help you work efficiently, and I only care if you eat on time

  • Under the head in the upper right cornerSecurity

A vscode plug-in, they help you work efficiently, and I only care if you eat on time

Create a new one inaccess tokensAttention!! thisaccess tokensOnly show once, later can not find, pay attention to the record, and createaccess tokensYou must select all permissions when publishing, otherwise an error will be reported in the publishing process
A vscode plug-in, they help you work efficiently, and I only care if you eat on time

release

After setting up the icon, editing the readme and changelog, and deleting some redundant files, you can upload them to the plug-in storeExtension MarketplaceIt was downloaded and used by others;

inputvsce create-publisher [name]
The [name] here is the organization that just created the accountorganizationsName, fill in the mailbox and the access token you just created

inputvsce publishYou can start uploading;

When you seeSuccessfully published ***When you upload, upload success!!


finish

Gayhub:https://github.com/kelrvins/remind-me

reference material: